java 8 stream List去重/集合去重

简介

本博文主要讲解在Java 8中 如何通过stream流的方式去重。
 

List<String>通过stream去重

List unique = list.stream().distinct().collect(Collectors.toList());

List<String>通过stream去重是非常简单的。就上面的一句代码搞定
 

List<对象>通过stream根据集合对象的某个属性或者某些属性去重

// Person 对象
public class Person {
    private String id;
    
    private String name;
    
    private String sex;

    <!--省略 get set-->
}

根据name去重

// 根据name去重
List<Person> unique = persons.stream().collect(
            Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
);

根据name sex两个属性去重

List<Person> unique = persons.stream().collect(
           Collectors. collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))), ArrayList::new)
);

原创文章,作者:306829225,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/243626.html

(0)
上一篇 2022年4月11日 21:46
下一篇 2022年4月11日 21:46

相关推荐

发表回复

登录后才能评论