方式一
1. distinct()不提供按照属性对对象列表进行去重的直接实现。它是基于hashCode()和equals()工作的。如果我们想要按照对象的属性,对对象列表进行去重,我们可以通过其它方法来实现
public static Predicate distinctByKey(Function super T, ?> keyExtractor) {
Map seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
2. 使用方法:用Stream接口的 filter()接收为参数
List lists = list.stream().filter(distinctByKey(b->b.getTid())).collect(Collectors.toList());
方式二
存在重复数据的问题,这里使用stream流的衍生功能,去除一个对象中的部分元素的重复如下:
ArrayList collect =records1.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(()-> new TreeSet<>(
Comparator.comparing(
ProductProcessDrawbackDto::getId))), ArrayList::new));
其中records1是处理的对象,改对象的list集合,collect是处理后返回的结果
其中的ProductProcessDrawbackDto是处理的list中每一个对象,id是判断是否重复的条件(去除id相同的重复元素,只保留一条)
多个字段或者多个条件去重
ArrayList collect1 =patentDtoList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(()-> new TreeSet<>(
Comparator.comparing(p->p.getPatentName() + ";" + p.getLevel()))), ArrayList::new)