Java8集合中的对象根据指定字段去重,并根据条件获取指定去重后的对象
一、distinct去重
List uniqueList = list.stream().distinct().collect(Collectors.toList());
二、collectingAndThen去重
一个字段:
ArrayList<PaperRecord> paperRecordList = list.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PaperRecord::getUserId))), ArrayList::new)
);
多个字段:
ArrayList<PaperRecord> paperRecordList = list.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(item->item.getUserId()+"_"+item.getPassStatus()))), ArrayList::new)
);
三、Collectors.toMap去重
去重取旧对象:
List<PaperRecord> paperRecordList = new ArrayList<>(list.stream()
.collect(Collectors.toMap(item -> item.getUserId(), Function.identity(), (oldValue, newValue) -> oldValue))
.values());
去重根据条件取对象:
List<PaperRecord> paperRecordList = new ArrayList<>(list.stream()
.collect(Collectors.toMap(item -> item.getUserId(), Function.identity(), (oldValue, newValue) -> oldValue.getPassStatus() ? oldValue : newValue))
.values());
文章介绍了在Java8中对集合对象进行去重的三种方法:使用distinct()方法,利用collectingAndThen()结合toCollection创建TreeSet,以及通过Collectors.toMap()。对于多个字段的去重,可以通过自定义比较器实现。同时,展示了如何根据特定条件选择去重后的对象。

8805

被折叠的 条评论
为什么被折叠?



