Published on

Group object by one of its property

Authors

Overview

This post will present you with a ways of grouping a User Define Object by one of its property. This is a common problem we face while coding lets take an example:

  • Case one where we have a list of users, and we need to group user by its age.
  • Another case where we need to organize user by its id

If you look close, you will see that in the first case we can have multiple users the same age, while in another case we always have only user against its id.

Let's look at the solutions with example POJO User class

public class User {
    private Long id;
    private String name;
    private Integer age;

    //getter-setter or lombok annotation
}

Group POJO by one of its property

We can do it in two different ways.

Group POJO by one of its property using traditional for loop

public static Map<Integer, List<User>> groupByAge(List<User> list) {
    Map<Integer, List<User>> groups = new HashMap<>();
    for (User user : list) {
        if (groups.containsKey(user.getAge())) {
            groups.put(user.getAge(), new ArrayList<>());
        }
        groups.get(user.getAge()).add(user);
    }
    return groups;
}

Group POJO by one of its property using groupingBy Collectors of collection stream

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

Arrange POJO by one of its unique property

Arrange POGO by one of its unique property using traditional java

public static Map<Long, User> arrangeById(List<User> list) {
    Map<Long, User> userIdMap = new HashMap<>();
    for (User user : list) {
        if (!userIdMap.containsKey(user.getId())) {
            userIdMap.put(user.getId(), user);
        }
    }
    return userIdMap;
}

Arrange POGO by one of its unique property using toMap Collectors of collection stream

Map<Long, User> userIdMap = list.stream().collect(Collectors.toMap(User::getId, user -> user, (a, b) -> b));

These kinds of object arrangement will be beneficial to decrease the number of iterations we need to take while looking for a same type of property