In this tutorial, we would be looking at the various examples of using streams introduced in Java 8 to create a Map from a List of values. I have been working with Java 8 for quite a while and have found streams extremely useful. Almost every single day I am writing code using streams. We would be looking at the various examples of creating a Map out of a List.
Convert List to Map Examples
1. Create a Map from List with Key as an attribute
We have a Person Object with an id attribute. So as to create a map from Person List with the key as the id of the Person we would do it as below.
1 2 3 4 5 6 |
private static void convertList2Map(List<Person> persons) { Map<Integer, Person> id2PersonMap =persons.stream() .collect(Collectors.toMap(Person::getId , Function.identity())); id2PersonMap.forEach((key, value) -> System.out.println(key + " : " + value)); } |
Function.identity() returns a function that returns its input parameter. I could have written the about conversion as below also
1 2 3 |
Map<Integer, Person> id2PersonMap =persons.stream() .collect(Collectors.toMap(Person::getId , string -> string)); // instead of Function.identity() |
2. Create a Map with duplicate key – List of values
We would like to group the list of Persons with same last name. Here is the example
1 2 3 4 5 |
private static void convertList2MapDuplicateKey(List<Person> persons) { Map<String, List<Person>> lastName2Persons =persons.stream() .collect(Collectors.groupingBy(Person::getLastName)); lastName2Persons.forEach((key, value) -> System.out.println(key + " : " + value)); } |
We have used Collectors.groupingBy().This is used for grouping the objects by an attribute and then return the results as map. And here we are grouping by the last name of the Person.
3. Create a Map with duplicate key – Set of unique values
Here we would group a list of Strings by the length. But we would like to group only the unique Strings. So we would create a Set of Strings
1 2 3 4 5 |
private static void convertList2Map() { Map<Integer, Set<String>> len2StringMap = Arrays.asList("Java", "Core Java", "Streams", "Java","Example").stream() .collect(Collectors.groupingBy(String::length,Collectors.mapping(Function.identity(),Collectors.toSet()))); len2StringMap.forEach((key, value) -> System.out.println(key + " : " + value)); } |
4. Create a Map for duplicate keys retaining only one value in map
We have a list of Strings with duplicates. We would create a map of the lengths of the Strings.
1 2 3 4 5 |
private static void convertList2MapRetainOneValue() { Map<String, Integer> len2StringMap = Arrays.asList("Java", "Example", "Core Java", "Streams", "Java","Example").stream() .collect(Collectors.toMap(Function.identity(), String::length, (oldValue,newValue) -> oldValue)); len2StringMap.forEach((key, value) -> System.out.println(key + " : " + value)); } |
5. Create a sorted Map for a sorted List
We have a sorted List and we would like to retain the sort order of the List in the Map also. So we would be creating a LinkedHashMap. A LinkedHashMap has a predictable order for iteration.
1 2 3 4 5 6 |
private static void convertList2MapSorted() { List<String> asList = Arrays.asList("Java", "Core Java", "Streams", "Java","Example").parallelStream().sorted().collect(Collectors.toList()); Map<String, Integer> len2StringMap = asList.stream() .collect(Collectors.toMap(Function.identity(), String::length, (oldValue,newValue) -> oldValue , LinkedHashMap::new)); len2StringMap.forEach((key, value) -> System.out.println(key + " : " + value)); } |
6. Create a Map of Map of Values
Let’s create a map of Persons first grouped by the country of a Person and then grouped by the last name of the person. Here we are grouping the first by country and then grouping them again by the last name.
1 2 3 4 5 |
private static void convertList2MapofMap(List<Person> persons) { Map<String, Map<String, List<Person>>> country2LastName2PersonMap =persons.stream() .collect(Collectors.groupingBy(Person::getCountry, Collectors.groupingBy(Person::getLastName))); country2LastName2PersonMap.forEach((key, value) -> System.out.println(key + " : " + value)); } |
Summary
As we saw various ways to create a Map of Items from a List of Items. I have found all the above methods very useful in my daily Java development and hope that it would be helpful for you also. If I am missing any of the other ways to convert a list to Map, please drop a comment.
Great examples. Just a simple mistake in the article. You are not using Function.getIdentity() but you mention it. Thanks.
Thanks for pointing out the mistake.This is what makes an article better. I have edited the article and corrected it.
I always keep searching for these simple and to the point examples. Have bookmarked this page. Thanks
Thanks alots. this is really helpful note.