java stream distinct() 按指定对象属性进行去重

方式一

1. distinct()不提供按照属性对对象列表进行去重的直接实现。它是基于hashCode()和equals()工作的。如果我们想要按照对象的属性,对对象列表进行去重,我们可以通过其它方法来实现

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object,Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
} 

  

2. 使用方法:用Stream接口的 filter()接收为参数

List<Entity> lists = list.stream().filter(distinctByKey(b->b.getTid())).collect(Collectors.toList());

 

方式二

存在重复数据的问题,这里使用stream流的衍生功能,去除一个对象中的部分元素的重复如下:

ArrayList<ProductProcessDrawbackDto> collect = records1.stream().collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(
                                Comparator.comparing(
                                        ProductProcessDrawbackDto::getId))), ArrayList::new));

其中records1是处理的对象,改对象的list集合,collect是处理后返回的结果

其中的ProductProcessDrawbackDto是处理的list中每一个对象,id是判断是否重复的条件(去除id相同的重复元素,只保留一条)

多个字段或者多个条件去重

 ArrayList<PatentDto> collect1 = patentDtoList.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(p->p.getPatentName() + ";" + p.getLevel()))), ArrayList::new)

 

 

参考:https://blog.csdn.net/yojofly/article/details/100986216

http://www.10qianwan.com/articledetail/605000.html

posted @ 2020-08-20 14:41  就这个名字好  阅读(30092)  评论(1编辑  收藏  举报