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)aa... 黑科技数据(WePoKe)aapoker有猫腻吗(透明挂黑科技)一贯真的有挂(2024已更新)(哔哩...
玩家必备科普!wepoke有吗... 玩家必备科普!wepoke有吗(软件透明挂)2025新版教程(2023已更新)(哔哩哔哩)1、每个玩...
黑科技实锤(智星德州菠萝app... 黑科技实锤(智星德州菠萝app下载)外挂透明挂辅助挂(透视)本来真的是有挂(有挂技术)-哔哩哔哩;1...
黑科技辅助!epoker外挂(... 黑科技辅助!epoker外挂(透视)高科技教程(2022已更新)(哔哩哔哩)暗藏猫腻,小编详细说明e...
黑科技讲解(WePoKe)wp... 黑科技讲解(WePoKe)wpk德州专用辅助器(透明挂)好像是有挂(2021已更新)(哔哩哔哩);w...
热点推荐!!wpk开挂实锤(a... 热点推荐!!wpk开挂实锤(ai辅助)技巧教程(2020已更新)(哔哩哔哩)1、快速入门:当你通过点...
黑科技辅助!云扑克内置辅助器(... 黑科技辅助!云扑克内置辅助器(透视)详细教程(2023已更新)(哔哩哔哩)1、每一步都需要思考,不同...
黑科技辅助(wepower德州... 黑科技辅助(wepower德州辅助器)外挂透明挂辅助工具(透视)确实存在有挂(今日头条)-哔哩哔哩;...
黑科技科技(WePoKe)德州... 黑科技科技(WePoKe)德州之星辅助器怎么用(辅助挂)真是是有挂(2021已更新)(哔哩哔哩)1、...
发现一款!!微扑克wpk辅助存... 发现一款!!微扑克wpk辅助存在吗(透明黑科技)系统教程(2025已更新)(哔哩哔哩);人气非常高,...