Map .

How To Convert List Into Map In Java 8

Written by Ben Javu Jan 07, 2023 ยท 4 min read
How To Convert List Into Map In Java 8

<pre> class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } List<Person> persons = new ArrayList<>(); persons.add(new Person("John", 25)); persons.add(new Person("Mary", 30)); persons.add(new Person("Peter", 35)); </pre>

Table of Contents

How to Convert a Map to a List in Java Example Tutorial
How to Convert a Map to a List in Java Example Tutorial from javarevisited.blogspot.com

Introduction

If you are a Java developer, then you must be familiar with the List and Map data structures. List is an ordered collection of elements while Map is a collection of key-value pairs. In this article, we will explore how to convert a List into a Map in Java 8.

Why Convert List into Map?

There are many use cases where we need to convert List into Map. For example, we may want to group objects based on a specific attribute, or we may want to create a lookup table for faster access to objects.

Step 1: Create a List

Let's start by creating a List of objects that we want to convert into a Map. For this example, we will create a simple Person class with name and age fields.

 class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } List persons = new ArrayList<>(); persons.add(new Person("John", 25)); persons.add(new Person("Mary", 30)); persons.add(new Person("Peter", 35)); 

Step 2: Convert List into Map using Collectors.toMap()

To convert List into Map in Java 8, we can use the Collectors.toMap() method. This method accepts two functions as arguments: one to extract the key from each element of the List, and another to extract the value from each element of the List.

 Map personsMap = persons.stream() .collect(Collectors.toMap(Person::getName, Person::getAge)); System.out.println(personsMap); 

In the above code, we are using the stream() method to convert the List into a Stream. Then we are calling the Collectors.toMap() method to convert the Stream into a Map. We are using Person::getName as the key extractor function and Person::getAge as the value extractor function.

Step 3: Handle Duplicate Keys

If the List contains duplicate keys, then the Collectors.toMap() method will throw an IllegalStateException. To avoid this, we can pass a third argument to the method which is a BinaryOperator that specifies how to merge the values of duplicate keys.

 persons.add(new Person("Mary", 40)); Map personsMap = persons.stream() .collect(Collectors.toMap(Person::getName, Person::getAge, (age1, age2) -> age1)); System.out.println(personsMap); 

In the above code, we have added a Person object with the name "Mary" and age 40. When we try to convert the List into a Map, we will get an IllegalStateException because there are duplicate keys. To handle this, we are passing a lambda expression that returns the first age (age1) in case of duplicate keys.

Step 4: Handle Null Values

If the List contains null values, then the Collectors.toMap() method will throw a NullPointerException. To avoid this, we can pass a fourth argument to the method which is a Supplier that specifies how to create a new Map.

 persons.add(null); Map personsMap = persons.stream() .filter(Objects::nonNull) .collect(Collectors.toMap(Person::getName, Person::getAge, (age1, age2) -> age1, LinkedHashMap::new)); System.out.println(personsMap); 

In the above code, we have added a null value to the List. When we try to convert the List into a Map, we will get a NullPointerException. To handle this, we are using the filter() method to remove the null values from the Stream. We are also passing a LinkedHashMap::new as the fourth argument to the Collectors.toMap() method to create a LinkedHashMap instead of a HashMap.

Conclusion

In this article, we have learned how to convert a List into a Map in Java 8 using the Collectors.toMap() method. We have also learned how to handle duplicate keys and null values. By mastering these techniques, we can write more efficient and concise code in our Java applications.

Question & Answer

Q: What is the difference between List and Map in Java?
A: List is an ordered collection of elements while Map is a collection of key-value pairs. In List, we access elements by their index while in Map, we access values by their key. Q: What is the benefit of converting List into Map in Java?
A: Converting List into Map can help us to group objects based on a specific attribute or to create a lookup table for faster access to objects. It can also help us to eliminate duplicates and to perform operations on the values of the Map.
Read next