美文网首页
Stream流中根据某个字段去重

Stream流中根据某个字段去重

作者: zhimin_ | 来源:发表于2023-09-18 09:26 被阅读0次

环境

JDK:1.8

处理方法

方法一

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

方法二
利用map. map.putIfAbsend(k , v) 的返回值特性

List<Person> persons = new ArrayList();
Map<String,Boolean> map = new HashMap();
List<Person> uniqueByName = persons.stream()
                      .filter(e -> map.putIfAbsend(e.getName, Boolean.TRUE)  ==  null)
                      .collect(Collector.toList()), 

相关文章

网友评论

      本文标题:Stream流中根据某个字段去重

      本文链接:https://www.haomeiwen.com/subject/abkgvdtx.html