Convert List to Map in Java

We often need to convert a list to a map in Java. In this lesson, you will learn how to do that with Java 8. If you are looking for more information on working with maps in Java, check out our tutorial on Map in Java.

Let’s say we have a list of User objects. 

User.class

class User {

  private String name;
  private String city;
  private String state;
  
 // constructors, getters, setters and toString() method
}


Now, we have a requirement to collect users based on a field. We can do that by converting the provided list into a map.

Convert List to Map with Java 8

In this example, we use the Java Streams API and the Collectors class to collect all users based on a “city”.

class Test {

  public static void main(String[] args) throws IOException {

    Map<String, List<User>> usersMap = getUsers().stream().collect(
           Collectors.groupingBy(User::getCity, HashMap::new, Collectors.toList()));

    System.out.println(usersMap.get("London"));
  }

  private static List getUsers() {
    List users = new ArrayList<>();
    users.add(new User("Tom", "London", "UK"));
    users.add(new User("Jim", "Paris", "France"));
    users.add(new User("Megan", "London", "UK"));
    users.add(new User("Melissa", "Birmingham", "UK"));
    users.add(new User("Steve", "Paris", "France"));

    return users;
  }
}
Output: [User{name=’Tom’, city=’London’, state=’UK’}, User{name=’Megan’, city=’London’, state=’UK’}]
 
The collect() method returns a Map object where the keys are city names (as returned by the getCity method) and the values are lists of User objects that live in that city.
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *