how-to · java · collections

How-to GROUP BY list of objects to map in java?

Problem:

You need to group list of objects by field to map by object field.
You have list of objects and need to group them by some field and get a Map<Field, List<Object>>.

Example

You have class User:

public class User {  
    private String name;
    private int age;
}

And have a List<User>

[User{name='John', age=27}, User{name='Mary', age=25}, User{name='Lucy', age=25}]

You want to group them by their ages to have a map Map<Integer, List<User>>:

{25=[User{name='Mary', age=25}, User{name='Lucy', age=25}], 27=[User{name='John', age=27}]}

Solution 1 (java 7 or less):

Map<Integer, List<User>> map = new HashMap<Integer, List<User>>();  
for (User user : users) {  
   Integer key = user.getAge();
   if (map.get(key) == null) {
      map.put(key, new ArrayList<User>());
   }
   map.get(key).add(user);
}

Solution 2 (java 8):

Map<Integer, List<User>> usersGroupedByAge = users.stream().collect(Collectors.groupingBy(User::getAge));  

Read Also:

Java8 Collectors documentation
M. Needham article about grouping.
JavaCollections documentation
[RUS] JavaCollections useful tips

Published:
comments powered by Disqus