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