使用stream流去除对象中的部分元素的重复

工作中遇到返回个一个list集合中,存在重复数据的问题,这里使用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<PatentDto> collect1 = patentDtoList.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        Comparator.comparing(p->p.getPatentName() + ";" + p.getLevel()))), ArrayList::new));

你可能感兴趣的:(使用stream流去除对象中的部分元素的重复)