How to filter and combine objects if they has same fields

Vlad Khurtin :

I've tried to solve the problem and am stuck. I have class User:

public class User {

   public String name;
   public String email;
   public Integer age;
   public String group;

   public User() {
   }

   public User(String name, String email, Integer age, String group) {
      this.name = name;
      this.email = email;
      this.age = age;
      this.group = group;
   }
}

And list of users looks like:

List<User> users = new ArrayList<>();
users.add(new User("Max" , "test@test", 20 , "n1"));
users.add(new User("John" , "list@test", 21 , "n2"));
users.add(new User("Nancy" , "must@test", 22 , "n3"));
users.add(new User("Nancy" , "must@test", 22 , "n4"));
users.add(new User("Max" , "test@test", 20 , "n5"));

But this list contains duplicate objects with a difference only in the group. So I need to combine duplicate objects to new object looks like :

User: name: "Max", email: "test@test" , age: 20, groups: "n1, n5"

User: name: "John", email: "list@test" , age: 21, groups: "n2"

User: name: "Nancy", email: "must@test" , age: 22, groups: "n3, n4"

I understand that I need to use steams from Java 8, but don't understand exactly how.

Please, help

Nicholas K :

You may simply do:

List<User> sortedUsers = new ArrayList<>();
// group by email-id
Map<String, List<User>> collectMap = 
                 users.stream().collect(Collectors.groupingBy(User::getEmail));

collectMap.entrySet().forEach(e -> {
    String group = e.getValue().stream()                     // collect group names
                               .map(i -> i.getGroup())
                               .collect(Collectors.joining(","));
    User user = e.getValue().get(0);
    sortedUsers.add(new User(user.getName(), user.getEmail(), user.getAge(), group));
});

which outputs:

[
   User [name=John, email=list@test, age=21, group=n2], 
   User [name=Max, email=test@test, age=20, group=n1,n5], 
   User [name=Nancy, email=must@test, age=22, group=n3,n4]
]

Make sure to add getters and setters, also override the toString() of User.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=129566&siteId=1