JavaJava 8Technology

Examples of Converting List to Map using Streams

Learn various ways of Collecting a Stream of List into Map using Java Streams API. Using Collectors.toMap and Collectors.groupingBy with example.

User and users List List<User>

Let’s consider, you have a User class and a List of the users which you want to convert to Map.

User.java

public class User {
    private Long id;
    private String name;
    private String lastName;
    private int age;

    ....
}

List of Users List<User>

List<User> users = Arrays.asList(
        new User(1l, "Bob", "Taylor", 30),
        new User(2l, "Tom", "Richard", 32),
        new User(3l, "Bob", "Wills", 31),
        new User(4l, "Nick", "Jackson", 29),
        new User(5l, "john", "Anderson", 31),
        new User(6l, "Tom", "Taylor", 30),
        new User(7l, "Bob", "Mills", 29)
);

Now, in the below sections, we will see how can we use Streams to convert the above list into different types of Maps.

Convert List to Simple Map using Streams Collectors.toMap()

The Java Stream Collectors.toMap() is a convenient method to create maps. The Method takes two lambda expressions. Out of which first is for key and the other for value. Obviously, you can replace Lambda Expressions by Method References.

Map<Long, String> map = users
        .stream()
        .collect
            (Collectors.toMap(User::getId, User::getLastName));

Note: the methods getId and getLastName are not static. However, they are referred in static way. Because, when you iterate a collection, like the one above, the Java Stream will smartly replace the Class Name with the instance of current object. Hence the call actually happens on the nth User in the list – where n is the index of current iteration.

Now, let’s print the output map.

map.entrySet().forEach(System.out::println);

-------- Output -------
1=Taylor
2=Richard
3=Wills
4=Jackson
5=Anderson
6=Taylor
7=Mills

Convert List<K> to Map<String, K> Using Streams Collections.toMap()

You saw, how to convert List to a simple map. Also, you learnt how can you refer to fields like User::getName or User::getAge and set any key and value pair for the output map. However, what if you want to store the entire User object as a value instead ?

For example: You want to create a map of Id to User.
List<User> ——-> Map<Long, User>

Map<Long, User> map = users
        .stream()
        .collect
            (Collectors.toMap(User::getId, Function.identity()));

Here, we have used Function.identity() to refer to the actual User instance. Where the identity returns a function that returns the input object. When we print the above map, we get:

1=[id: 1, name: Bob, last name: Taylor, age: 30]
2=[id: 2, name: Tom, last name: Richard, age: 32]
3=[id: 3, name: Bob, last name: Wills, age: 31]
4=[id: 4, name: Nick, last name: Jackson, age: 29]
5=[id: 5, name: john, last name: Anderson, age: 31]
6=[id: 6, name: Tom, last name: Taylor, age: 30]
7=[id: 7, name: Bob, last name: Mills, age: 29]

How to group by a Field using Stream groupingBy

Many a times, we have to iterate through a Collection and group by id or any other field. To demonstrate we will iterate the above list of users to group by users with same name.

List<Users> ————> Map<String, List<User>>

Map<String, List<User>> groupedByName = users
        .stream()
        .collect
            (Collectors.groupingBy(User::getName));

Here, we have used Collectors.groupingBy and passed a Method Reference to users name.
And, the output we get:

Tom=[[id: 2, name: Tom, last name: Richard, age: 32], [id: 6, name: Tom, last name: Taylor, age: 30]]
Bob=[[id: 1, name: Bob, last name: Taylor, age: 30], [id: 3, name: Bob, last name: Wills, age: 31], [id: 7, name: Bob, last name: Mills, age: 29]]
Nick=[[id: 4, name: Nick, last name: Jackson, age: 29]]
john=[[id: 5, name: john, last name: Anderson, age: 31]]

Summary

In this short tutorial of Convert List to Map Using Java Streams, you learnt how can you iterate through Stream and use Collectors to get various types of Maps from the same list.


One thought on “Examples of Converting List to Map using Streams

  1. Hello there,

    My name is George, and I was wondering if you would like to have your website amitph.com promoted as a resource on my blog georgemartjr.com ?

    We are updating our broken link resources to include up to date resources for our readers. Our resource links are manually approved as a do follow link.
    If you are interested in having your site included as a resource on our blog, please let me know.

    Thanks for your consideration,
    George

Comments are closed.