Stream流中根据某个字段去重

环境

JDK:1.8

处理方法

方法一

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

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

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

你可能感兴趣的:(Stream流中根据某个字段去重)