Java Programming Tutorials

Java programming tutorials with many code examples!

Java 8 List to Map

Very common task is creation of Map from a List of objects. In this post we show how to use Java 8 to convert List to Map using Collectors.

Sample data for processing in collections

This is our sample class that we we’ll use to create mappings:

package com.farenda.java.util;

public class User {
    private static long userCounter;
    private long id;
    private final String name;

    public User(String name) {
        this.id = userCounter++;
        this.name = name;
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "User(id:" + id + ", name: " + name + ")";
    }
}

Pre Java 8 List to Map

Before Java 8 the standard way to convert List to Map was to use for-each loop like so:

List<User> users = asList(new User("Foo"), new User("Bar"));
Map<String, User> usersByName = new HashMap<>();
for (User user : users) {
    usersByName.put(user.getName(), user);
}
System.out.println("Mapping: " + usersByName);

In the above code we’ve created a mapping from user’s name to user. This is the result:

Mapping: {Bar=User(id:1, name: Bar), Foo=User(id:0, name: Foo)}

Java 8 List to Map using Collector

Since Java 8 there’s a great way to convert List to Map using java.util.stream.Collectors.toMap. There are three versions of this Collector, but here we’ll use the simplest one:

List<User> users = asList(new User("Foo"), new User("Bar"));
Map<String, User> usersByName = users.stream()
    .collect(toMap(User::getName, Function.identity()));
System.out.println("Mapping: " + usersByName);

The toMap Collector takes two functions, both taking User as parameter:

  • the first one should create Map key from the parameter,
  • the second one should create Map value from the parameter.

In the example we use User.getName() to create Map key and Function.identity(), which just returns given parameter as is, to create Map value.

The above code produces the following output:

Mapping: {Bar=User(id:1, name: Bar), Foo=User(id:0, name: Foo)}

References:

Share with the World!