Java 8 streams – List to Map examples

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.

Function.identity() returns a function that returns its input parameter. I could have written the about conversion as below also

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

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

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.

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.

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.

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.

3 thoughts to “Java 8 streams – List to Map examples”

Leave a Reply