Stream流中根据某个字段去重

2023-09-18  本文已影响0人  zhimin_

环境

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()), 

上一篇 下一篇

猜你喜欢

热点阅读