使用Java8的stream对list中的对象进行去重

Java基础

浏览数:484

2020-6-15

首先我们有一个对象属性如下

@Data
public class Person {
    private String id;
    private String name;
    private String sex;
}

我们根据属性name来去重,去重代码如下

List<Person> persons = new ArrayList();
//赋值初始化过程省略
List<Person> uniqueByName = persons.stream().collect(
            Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);

根据name,sex两个属性去重

List<Person> persons = new ArrayList();
//赋值初始化过程省略
List<Person> uniqueByNameAndSex = persons.stream().collect(
           Collectors. collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new)
);

作者:君莫笑