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); 

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

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

相关内容

热门资讯

wepower有外挂!hhpo... wepower有外挂!hhpoker德州有挂(透视)存在挂教程(有挂猫腻)-哔哩哔哩;1、超多福利:...
wepokeai机器人!wej... wepokeai机器人!wejoker透视方法(透视)细节揭秘(确实有挂)-哔哩哔哩;亲真的是有正版...
wepokeai代打的胜率!p... wepokeai代打的胜率!pokermaster脚本(透视)黑科技教程(有挂秘笈)-哔哩哔哩是一款...
wepoke黑科技!德普之星透... wepoke黑科技!德普之星透视辅助软件是真的(透视)教你攻略(有挂方略)-哔哩哔哩是一款可以让一直...
wepoke是真的有挂!hh ... wepoke是真的有挂!hh poker辅助有用(透视)细节方法(有挂功能)-哔哩哔哩;最新版202...
wepokeai代打逻辑!po... wepokeai代打逻辑!pokemmo手机版脚本免费(透视)透明教程(真的有挂)-哔哩哔哩;是一款...
wepoke有app软件!we... wepoke有app软件!wepoker辅助工具(透视)透牌教程(有挂分析)-哔哩哔哩;wepoke...
wepok软件透明挂!哈糖大菠... 【福星临门,好运相随】;wepok软件透明挂!哈糖大菠萝软件下载(透视)2025新版教程(揭秘有挂)...
七分钟了解!新畅游互娱科技(辅... 七分钟了解!新畅游互娱科技(辅助挂)详细透视开挂辅助新2025版(切实真的有挂)-哔哩哔哩;1、首先...
wepokeai代打逻辑!德州... wepokeai代打逻辑!德州hhpoker脚本(透视)辅助教程(有挂秘笈)-哔哩哔哩;是一款可以让...