Stream去重整理
分两部分整理:
https://juejin.cn/post/6844903842132262926
- 基于Stream中对象去重
1. Stream 的distinct()
方法
distinct()
是Java 8 中 Stream 提供的方法,返回的是由该流中不同元素组成的流。distinct()
使用 hashCode()
和 eqauls()
方法来获取不同的元素。因此,需要去重的类必须实现 hashCode()
和 equals()
方法。换句话讲,我们可以通过重写定制的 hashCode()
和 equals()
方法来达到某些特殊需求的去重。
@Test public void listDistinctByStreamDistinct() { // 1. 对于 String 列表去重 List<String> stringList = new ArrayList<String>() {{ add("A"); add("A"); add("B"); add("B"); add("C"); }}; out.print("去重前:"); for (String s : stringList) { out.print(s); } out.println(); stringList = stringList.stream().distinct().collect(Collectors.toList()); out.print("去重后:"); for (String s : stringList) { out.print(s); } out.println(); }
去重前:AABBC
去重后:ABC
- 基于Stream对象属性属性
@Test public void distinctByProperty1() throws JsonProcessingException { // 这里第一种方法我们通过新创建一个只有不同元素列表来实现根据对象某个属性去重 ObjectMapper objectMapper = new ObjectMapper(); List<Student> studentList = getStudentList(); out.print("去重前 :"); out.println(objectMapper.writeValueAsString(studentList)); studentList = studentList.stream().distinct().collect(Collectors.toList()); out.print("distinct去重后:"); out.println(objectMapper.writeValueAsString(studentList)); // 这里我们引入了两个静态方法,以及通过 TreeSet<> 来达到获取不同元素的效果 // 1. import static java.util.stream.Collectors.collectingAndThen; // 2. import static java.util.stream.Collectors.toCollection; studentList = studentList.stream().collect( collectingAndThen( toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new) ); out.print("根据名字去重后 :"); out.println(objectMapper.writeValueAsString(studentList)); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?