遇到同时通过多个字段对list进行去重需求,记录一下
@Data
public class User {
private Long id;
private String name;
private String code;
private String phone;
private Integer age;
public User(Long id, String name, String code, String phone, Integer age) {
this.id = id;
this.name = name;
this.code = code;
this.phone = phone;
this.age = age;
}
public User() {}
}
List<User> userList = new ArrayList<>();
userList.add(new User(1L, "张三", "1001", "99999999", 21));
userList.add(new User(1L, "张三", "1001", "99999999", 21)); // 重复
userList.add(new User(3L, "张三", "1001", "99999999", 22));
userList.add(new User(4L, "张三", "1001", "99999999", 21));
userList.add(new User(5L, "张四", "1002", "88888888", 21));
List<User> list = userList.stream()
.distinct() // 使用默认的equals方法进行去重
.collect(Collectors.toList());
输出:
[User(id=1, name=张三, code=1001, phone=99999999, age=21),
User(id=3, name=张三, code=1001, phone=99999999, age=22),
User(id=4, name=张三, code=1001, phone=99999999, age=21),
User(id=5, name=张四, code=1002, phone=88888888, age=21)]
List<User> list = userList.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
new TreeSet<>
(Comparator.comparing(User::getName)
.thenComparing(User::getCode)
.thenComparing(User::getPhone))),
ArrayList::new));
以上是使用Collectors.collectingAndThen
收集器将流中的元素收集到一个TreeSet
中。这个TreeSet
会根据User
对象的name
、code
和phone
字段进行排序和去重。最后,再使用ArrayList::new
将排序后的TreeSet
中的元素收集到一个新的ArrayList
中。
输出结果:
[User(id=1, name=张三, code=1001, phone=99999999, age=21),
User(id=5, name=张四, code=1002, phone=88888888, age=21)]
可以看到结果都去重成功了