Lambda表达式,List对象集合去重
1.创建实体
1 2 3 4 5 6 7 8 9 10 11 12 | @Data @NoArgsConstructor @AllArgsConstructor @Builder public class EmployeeDto { private String id; private String name; private String no_id; private String dept; private int year; private EmpInfoPo info; } |
2.List实体数据
1 2 3 4 5 6 | { "dept" : "研发部1" , "id" : "001" , "name" : "员工1号" , "no_id" : "YF001" , "year" :2} { "dept" : "研发部2" , "id" : "002" , "name" : "员工2号" , "no_id" : "YF001" , "year" :5} { "dept" : "研发部3" , "id" : "003" , "name" : "员工3号" , "no_id" : "YF001" , "year" :7} { "dept" : "研发部4" , "id" : "004" , "name" : "员工4号" , "no_id" : "YF001" , "year" :6} { "dept" : "研发部5" , "id" : "005" , "name" : "员工5号" , "no_id" : "YF001" , "year" :4} { "dept" : "研发部6" , "id" : "006" , "name" : "员工1号" , "no_id" : "YF001" , "year" :2} |
3.Lambda方式去重
集合方式排序、stream方式排序对比
Collectors.collectingAndThen()数据流转处理函数
distinctByKey()自定义比较器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | /** * 函数去重 利用TreeSet无重复特性 * collect 收集器 * Collectors 收集器的方法 */ public static void exceptRepeatV1(List<EmployeeDto> employeeList){ ArrayList<EmployeeDto> collect = employeeList .stream() .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(EmployeeDto::getName))), ArrayList:: new )); print(collect); } /** * 自定义方式去重 * @param employeeList */ public static void exceptRepeatV2(List<EmployeeDto> employeeList){ List<EmployeeDto> collect = employeeList.stream() .filter(distinctByKey(e -> e.getName())) .collect(Collectors.toList()); print(collect); } /** * 自定义比较方法 * @param keyExtractor * @param <T> * @return */ private static <T> Predicate<T> distinctByKey(Function<? super T,?> keyExtractor){ Map<Object,Boolean> map= new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE)== null ; } |
转载自:https://blog.csdn.net/Oaklkm/article/details/127074712
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
2017-04-12 yii2:redis调用