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

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

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

相关内容

热门资讯

透视辅助!智星德州菠萝插件官网... 透视辅助!智星德州菠萝插件官网,智星菠萝有挂吗,wepoke教程(真是真的是有挂)1、该软件可以轻松...
透视游戏“wpk辅助软件”真是... 透视游戏“wpk辅助软件”真是存在有挂(辅助挂)详细辅助曝光教程1、实时开挂更新:用户可以随时随地访...
wpk辅助购买!wepoker... wpk辅助购买!wepoker有插件吗,wepoker辅助工具(详细辅助高科技教程)1、不需要AI权...
透视美元局!wepoker透视... 1、透视美元局!wepoker透视脚本,wepoker模拟器哪个(详细辅助系统教程)2、进入游戏-大...
透视有挂!hhpoker透视方... 透视有挂!hhpoker透视方法,hhpoker透视方法,普及教程(都是是有挂)1、每一步都需要思考...
透视规律“wpk辅助器”切实真... 透视规律“wpk辅助器”切实真的有挂(辅助挂)详细辅助实用技巧1、系统规律教程、辅助透视等服务,为用...
wepoker透视脚本安卓!h... wepoker透视脚本安卓!hhpoker到底可以作弊码,智星菠萝辅助器(详细辅助爆料教程)1)we...
透视工具!wpk有没有脚本,如... 透视工具!wpk有没有脚本,如何下载wpk透视版,透明挂教程(其实真的是有挂)1、下载好wpk有没有...
透视辅助!wpk辅助插件叫什么... 透视辅助!wpk辅助插件叫什么,aapoker插件下载(详细辅助切实教程)是由北京得aapoker插...
红龙poker脚本!wepok... 红龙poker脚本!wepoker透视苹果系统,aapoker辅助挂(详细辅助扑克教程)1、这是跨平...