如果对象具有相同的字段,如何过滤和组合对象

时间:2019-05-16 11:06:43

标签: java list collections java-8 java-stream

我试图解决问题并陷入困境。我有班级用户:

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;
   }
}

用户列表如下:

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"));

但是此列表包含重复的对象,仅在组中有所不同。因此,我需要将重复的对象合并为新的对象,如下所示:

  

用户:姓名:“ Max”,电子邮件地址:“ test @ test”,年龄:20,组:“ n1,n5”

     

用户:姓名:“ John”,电子邮件地址:“ list @ test”,年龄:21岁,组:“ n2”

     

用户:姓名:“ Nancy”,电子邮件:“ must @ test”,年龄:22岁,组:“ n3,n4”

我了解到我需要使用Java 8中的流,但是不完全了解如何做。

请帮助

3 个答案:

答案 0 :(得分:2)

您可以利用toMap收集器,因为它具有合并功能,它将合并您的重复对象,例如,每次发现重复对象时我都会创建一个新对象,但是您可以修改现有对象

static User join(User a, User b) {
    return new User(a.getName(), a.getEmail(), a.getAge(), a.getGroup() + "," + b.getGroup());
}

和流操作。

List<User> collect = users.stream()
            .collect(Collectors.collectingAndThen(Collectors.toMap(User::getEmail,
                            Function.identity(), 
                            (a, b) -> join(a, b)),
                    map -> new ArrayList<>(map.values())));

答案 1 :(得分:1)

这是您需要的一个有效示例(我希望:))。

它将前三个字段的组合视为唯一键。然后,它将遍历列表,并基于键并将组作为值将“用户”添加到地图。我使用地图是因为它使检索速度更快。在插入新用户之前,我检查它是否已经在地图中。如果是这样,那么我将追加新的组。如果不是,请将其插入当前组。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class User {

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

    public static final void main(String[] args) {
        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"));

        List<User> filtered = filter(users);
        filtered.stream().forEach(System.out::println);
    }

    public User() {
    }

    public User(String key, String group) {
        String[] keys = key.split("-");
        this.name = keys[0];
        this.email = keys[1];
        this.age = Integer.parseInt(keys[2]);
        this.group = group;
    }

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

    public String toString() {
        return name + " : " + email + " : " + " : " + age + " : " + group;
    }

    public String getUniqueKey() {
        return name + "-" + email + "-" + age;
    }

    public static List<User> filter(List<User> users) {
        Map<String, String> uniqueGroup = new HashMap<>();
        for (User user : users) {
            String found = uniqueGroup.get(user.getUniqueKey());
            if (null == found) {
                uniqueGroup.put(user.getUniqueKey(), user.group);
            } else {
                uniqueGroup.put(user.getUniqueKey(), found + ", " + user.group);
            }
        }

        List<User> newUsers = new ArrayList<>();
        for (String key : uniqueGroup.keySet()) {
            newUsers.add(new User(key, uniqueGroup.get(key)));
        }

        return newUsers;
    }

}

答案 2 :(得分:1)

您可以简单地这样做:

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));
});

输出:

[
   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]
]

请确保添加getter和setter,也要覆盖User的toString()