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

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

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

在获取任务的时候,会出现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

相关推荐
+VX:Fegn08958 小时前
计算机毕业设计|基于springboot + vue旅游管理系统(源码+数据库+文档)
java·开发语言·vue.js·spring boot·课程设计
需要8268 小时前
MySQL 索引 B+ 树与“查询为什么变慢了
java·spring boot·spring·spring cloud·tomcat
一 乐8 小时前
二手交易平台|基于springboot + vue二手交易平台(源码+数据库+文档)
java·数据库·vue.js·spring boot·小程序
万年咸鱼8 小时前
编译Java源程序
java
Wang's Blog9 小时前
Java 项目实战: 外卖平台-删除分类的关联校验与自定义业务异常
java·服务器·项目开发
hai_android9 小时前
Kotlin / Android 常用函数使用示例手册
android·java·kotlin
MayBaymax9 小时前
MongoDB 索引与事务
java·数据库·mongodb
vx-程序开发9 小时前
【计算机毕设】django校园跑腿服务系统83141
java·数据库·vue.js·spring boot·spring·elasticsearch·django
勇气要爆发9 小时前
006.注解
java·注解
liuchangng10 小时前
Jev 模型研究:从生成式大模型到决策式模型——System One、RLCD 校准与采用边界
java·javascript·人工智能·python·深度学习