We often need to convert list to map in Java. In this lesson, you will learn how to do that with Java 8.
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’}]
That’s it!