java8List集合根据对象的属性去重

复制代码
import static java.util.Comparator.comparingLong;

import static java.util.stream.Collectors.collectingAndThen;

import static java.util.stream.Collectors.toCollection;

// 根据id去重

     List<Person> unique = persons.stream().collect(

                collectingAndThen(

                        toCollection(() -> new TreeSet<>(comparingLong(Person::getId))), ArrayList::new)

        );
复制代码

分析:

collect是一个终端操作,它接收的参数是将流中的元素累积到汇总结果的各种方式(称为收集器)

预定义收集器包括将流元素归约和汇总到一个值.如下

工厂方法                返回类型                  

collectingAndThen   转换函数返回的类型   包裹另一个转换器,对其结果应用转换函数

示例:Int count=Menu.getMenus.stream().collect(collectingAndThen(toList(),List::size))

 

toCollection            Collection<T>            把流中所有元素收集到给定的供应源创建的集合中

示例:ArrayList<Menu> menus=Menu.getMenus.stream().collect(Collectors.toCollection(ArrayList::new))

 

Comparator.comparing(Function keyExtractor)生成1Comparator对象,要求keyExtractor.apply()返回值一定要实现Comparable接口。从Student对象中提取id属性,而idint类型(Integer实现了Comparable)comparingDouble()comparingLong()comparingInt()不过是comparing()更具体的版本,使用方式相同。如果是字符串比较用Comparator.comparing(Human::getName)

posted @   枫树湾河桥  阅读(12085)  评论(0编辑  收藏  举报
编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
Live2D
欢迎阅读『java8List集合根据对象的属性去重』
西雅图
17:15发布
西雅图
17:15发布
6°
东北风
2级
空气质量
相对湿度
86%
今天
多云
3°/15°
周四
4°/16°
周五
4°/14°
点击右上角即可分享
微信分享提示