使用 Stream 流对集合根据对象的指定属性去重

默认的 Stream 去重不能根据对象属性去重

  1. 创建一个类
import lombok.Data;

@Data
public class Person {
    public Person() {}
    public Person(String name, Boolean gender, Integer age, float score) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.score = score;
    }
    public Person(String name, Boolean gender) {
        this.name = name;
        this.gender = gender;
    }
    private String name;
    private Boolean gender;
    private Integer age;
    private float score;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", gender=" + gender +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}
  1. 去重
import java.util.*;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

public class StreamDeduplicationTest {
    public static void main(String[] args) {
        Person p1 = new Person("zhangsan",false,19,60);
        Person p2 = new Person("lisi",true,20,80);
        Person p3 = new Person("wangmazi",false,28,70);
        Person p4 = new Person("meiyoule",true,15,50);
        Person p5 = new Person("evsd",true);
        Person p6 = new Person("evsd",true);

        List<Person> personList = Arrays.asList(p1,p2,p3,p4,p5,p6);
        ArrayList<Person> collect1 = personList.stream().collect(
                // 将集合先放到 treeSet 集合然后将他们转换成数组
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName())))
                        , ArrayList::new));
        collect1.forEach(System.out::println);
    }
}

posted @ 2020-11-24 15:50  vwa  阅读(7307)  评论(0编辑  收藏  举报