Java-两个集合取差集(4种方式)
创始人
2025-01-15 21:34:13
0

开发中比较两个集合的不同点,例如需要对于两个集合取差集,下面列举了几种方式。

方式1:使用Java 8的Stream流

整个集合过滤
   List list1 = Arrays.asList("a", "b", "c", "d");    List list2 = Arrays.asList("c", "d", "e", "f");     // 获取差集    List difference1 = list1.stream()        .filter(element -> !list2.contains(element))        .collect(Collectors.toList());     // 获取list2中不在list1的元素    List difference2 = list2.stream()        .filter(element -> !list1.contains(element))        .collect(Collectors.toList()); 
根据集合中对象的属性来过滤
   // 根据集合中对象的name属性来过滤     public void testStreamNoneMatch(List originalDto, List newDto) {         List boy = originalDto.stream()                 .filter(item -> item.getGender() == 1                         && newDto.stream().anyMatch(dto -> dto.getName().equals(item.getName()))).collect(Collectors.toList());         log.info("性别为男生,且名字相同的人员为{}", JSONObject.toJSONString(boy));     } 

方式2:使用Java集合类的removeAll()方法

   List list1Copy = new ArrayList<>(list1);    List list2Copy = new ArrayList<>(list2);     // 获取list1中不在list2的元素    list1Copy.removeAll(list2);    List difference1 = list1Copy;     // 获取list2中不在list1的元素    list2Copy.removeAll(list1);    List difference2 = list2Copy; 

方式3:使用Google Guava库的Sets.difference()方法

 List list1 = ...;    List list2 = ...;     // 获取list1中不在list2的元素    Set set1 = Sets.newHashSet(list1);    Set set2 = Sets.newHashSet(list2);    Set difference1 = Sets.difference(set1, set2);     // 获取list2中不在list1的元素    Set difference2 = Sets.difference(set2, set1); 

方式4:使用Apache Commons Collections的ListUtils.subtract()方法

   List list1 = ...;    List list2 = ...;     // 获取list1中不在list2的元素    List difference1 = ListUtils.subtract(list1, list2);     // 获取list2中不在list1的元素    List difference2 = ListUtils.subtract(list2, list1); 

注意:方式有很多,大家可根据项目需求和已引入的库,选择合适的方法来计算集合的差集。

有更好的方式或想法,欢迎大家评论区留言,互相学习~

相关内容

热门资讯

透视苹果版!wpk透视辅助方法... 透视苹果版!wpk透视辅助方法,wpk辅助是什么,曝光教程(好像真的是有挂);亲,关键说明,wpk透...
透视教程!hhpoker德州透... 透视教程!hhpoker德州透视挂,hhpoker的辅助是真的吗,曝光教程(有挂插件);1、hhpo...
透视讲解!aapoker脚本,... 透视讲解!aapoker脚本,aapoker透视插件,教你攻略(有挂规律)1、aapoker透视插件...
透视脚本!如何下载wpk透视版... 透视脚本!如何下载wpk透视版,wpk透视是真的吗,2025新版总结(原来真的有挂)一、如何下载wp...
透视工具!hhpoker作弊实... 透视工具!hhpoker作弊实战视频,hhpoker脚本,透牌教程(有挂工具)1)hhpoker作弊...
透视好牌!aapoker辅助器... 透视好牌!aapoker辅助器是真的吗,aapoker怎么选牌,新2025教程(有挂脚本)aapok...
透视规律!德州hhpoker脚... 透视规律!德州hhpoker脚本,hhpoker辅助挂,曝光教程(有挂技巧)1、德州hhpoker脚...
透视私人局!wpk模拟器多开,... 透视私人局!wpk模拟器多开,wpk辅助,专业教程(竟然真的有挂);1、wpk模拟器多开系统规律教程...
透视辅助!aapoker脚本,... 透视辅助!aapoker脚本,aapoker怎么拿好牌,技巧教程(有挂介绍);1、每一步都需要思考,...
透视安卓版!hh poker辅... 透视安卓版!hh poker辅助有用吗,hhpoker是内部控制吗,安装教程(有挂揭秘)1、首先打开...