Java8两个集合(List)取交集、并集、差集、去重并集

import java.util.ArrayList;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**

  • @author billzhen
  • @version 1.0.0 *
  • @date 2024/6/17 14:44
    **/
    public class CollectionsTest {
    public static void main(String[] args) {
    List list1 = new ArrayList<>();
    list1.add("1");
    list1.add("2");
    list1.add("3");
    list1.add("4");
    list1.add("5");
    List list2 = new ArrayList<>();
    list2.add("2");
    list2.add("3");
    list2.add("6");
    list2.add("7");
    // 交集
    List intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
    System.out.println("---交集 intersection---");
    intersection.parallelStream().forEach(System.out::println);
    // 差集 (list1 - list2)
    List reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
    System.out.println("---差集 reduce1 (list1 - list2)---");
    reduce1.parallelStream().forEach(System.out::println);
    // 差集 (list2 - list1)
    List reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());
    System.out.println("---差集 reduce2 (list2 - list1)---");
    reduce2.parallelStream().forEach(System.out::println);
    // 并集
    List listAll = list1.parallelStream().collect(toList());
    List listAll2 = list2.parallelStream().collect(toList());
    listAll.addAll(listAll2);
    System.out.println("---并集 listAll---");
    listAll.parallelStream().forEachOrdered(System.out::println);
    // 去重并集
    List listAllDistinct = listAll.stream().distinct().collect(toList());
    System.out.println("---得到去重并集 listAllDistinct---");
    listAllDistinct.parallelStream().forEachOrdered(System.out::println);
    }
    }
相关推荐
两码事3 分钟前
告别繁琐的飞书表格API调用,让飞书表格操作像操作Java对象一样简单!
java·后端
R-G-B23 分钟前
OpenCV Python——报错AttributeError: module ‘cv2‘ has no attribute ‘bgsegm‘,解决办法
人工智能·python·opencv·opencv python·attributeerror·module ‘cv2‘·no attribute
DavieLau30 分钟前
C#项目WCF接口暴露调用及SOAP接口请求测试(Python版)
xml·服务器·开发语言·python·c#
灵魂猎手1 小时前
2. MyBatis 参数处理机制:从 execute 方法到参数流转全解析
java·后端·源码
灵魂猎手1 小时前
1. Mybatis Mapper动态代理创建&实现
java·后端·源码
Hard but lovely1 小时前
C++:stl-> list的模拟实现
开发语言·c++·stl·list
白露与泡影1 小时前
Spring容器初始化源码解析
java·python·spring
码界筑梦坊2 小时前
98-基于Python的网上厨房美食推荐系统
开发语言·python·美食
参宿72 小时前
electron之win/mac通知免打扰
java·前端·electron
计算机源码社2 小时前
分享一个基于Hadoop的二手房销售签约数据分析与可视化系统,基于Python可视化的二手房销售数据分析平台
大数据·hadoop·python·数据分析·毕业设计项目·毕业设计源码·计算机毕设选题