使用Java8 Stream流中的Collectors.collectingAndThen()方法去重

Collectors.collectingAndThen() 根据对象属性进行去重操作

Collectors.collectingAndThen()方法属于java8 Stream流中的java.util.stream.Collectors,此类实现了 java.util.stream.Collector接口,还提供了大量的方法对Stream流中的元素进行map和reduce 操作

在获取任务的时候,会出现id重复的状况,利用**Collectors.collectingAndThen()**进行去重,

java 复制代码
List<YearTargetTypePo> allYearTargetTypePos = this.selectList(new EntityWrapper<YearTargetTypePo>()
                                                            .eq("SYFW", RangeEnum.all.getValue())
                                                            .or().eq("CJBMID", user.getDepartmentId()));
typePoList.addAll(allYearTargetTypePos);
//        去掉重复的任务
newList = typePoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                () -> new TreeSet<>(Comparator.comparing(YearTargetTypePo::getId))), ArrayList::new));

以上使用到了**collectingAndThen()**根据属性进行去重的操作,进行结果集的收集,收集到结果集之后再进行下一步的处理。在这个去重操作中还用到了toCollection、TreeSet两个操作。

java 复制代码
public static<T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream,Function<R,RR> finisher)

看源码中需要传的参数有两个,第一个参数是Collector的子类,所以Collectors类中的大多数方法都能使用,比如:toList(),toSet(),toMap()等,当然也包括collectingAndThen()。第二个参数是一个Function函数,也是去重的关键,用到的ArrayList::new调用到了ArrayList的有参构造。Function函数是R apply(T t),在第一个参数downstream放在第二个参数Function函数的参数里面,将结果设置为t。对于toCollection是一个通用的方法,满足treeSet收集集合,再传入需要根据某个属性进行比较的比较器,就能达到去重的效果。

原文链接:

https://blog.csdn.net/qq_40474184/article/details/122043378

相关推荐
憧憬成为java架构高手的小白8 分钟前
langchain4j手敲理解
java·langchain
10mAh1 小时前
【Java】ArrayList 遍历删除为什么报错?三种写法与漏删复现
java·开发语言·windows
thefool1122661 小时前
多线程 4
java
Rain的Java大神之路1 小时前
[特殊字符]8年Java老兵转型AI Agent:90%的人挂在同一个坑,根本不用学Python!(万字实战复盘,建议收藏)
java·数据库·人工智能·后端·python·spring·ai编程
高级程序源2 小时前
springboot大学生体测系统72170-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·django·课程设计
IT研究室2 小时前
最新计算机毕业设计选题推荐-基于spring boot的文学名著分享系统-网站-文档指导-Java-springboot
java·spring boot·课程设计
denlaku2 小时前
JDK 13 新特性详解
java·开发语言
秋饼2 小时前
Java 后端企业级 LLM 网关实战:Spring Cloud Gateway 构建统一大模型接入层
java·ai·技术分享·后端开发
今年下半年2 小时前
【防重放】Spring Boot 通过自定义注解实现接口防重放
java·spring boot·自定义注解·防重放
WeiXin_DZbishe2 小时前
基于Node.js的马拉松赛事管理系统的设计与实现-计算机毕设 附源码【课程设计】90211
java·javascript·vue.js·python·php·课程设计