使用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

相关推荐
摇滚侠17 分钟前
《SpringBoot 3:入门与应用实战》第 9 章 使用 WebMvc 开发应用 阅读笔记 2
java·spring boot·笔记
technology_x37 分钟前
液冷超充站设备厂家哪家好?2026年功率与散热对比
java·开发语言
LayZhangStrive1 小时前
Agent开发 - MCP Client使用MCP Server的几种方式(Spring AI)
java·spring ai·mcp
仓三1 小时前
从 Prompt Engineering 到 Context Engineering:2026 年 Agent 性能提升的隐藏杠杆
java·prompt·context
许彰午1 小时前
07-SqlBuilder六法
java·开发语言·低代码·架构
孙6903421 小时前
Spring 注入多例 Bean
java·spring
Jul1en_1 小时前
【Java 脚手架】封装通用工具类-3
java·开发语言·redis·缓存·ai·bootstrap·rabbitmq
边境悍匪2 小时前
springboot常用注解
java·spring boot·学习
captain3762 小时前
文件与IO(2)
java·开发语言·windows·java-ee
mqiqe3 小时前
AgentScope Java 2.0 集成 Chat Completions Web:一行依赖让你的 Agent 变身 OpenAI 兼容服务
java·开发语言·前端