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 分钟前
python自动化-pytest-用例发现规则和要求
后端·python
YUELEI11833 分钟前
langchain 提示模版 PromptTemplate
python·langchain
liliangcsdn37 分钟前
结合prompt分析NodeRAG的build过程
java·服务器·人工智能·数据分析·知识图谱
东方不败之鸭梨的测试笔记37 分钟前
LangChain: Models, Prompts 模型和提示词
人工智能·python·langchain
黑色的山岗在沉睡1 小时前
LeetCode 189. 轮转数组
java·算法·leetcode
会飞的小蛮猪1 小时前
Jenkins运维之路(权限分配&忘记admin密码)
java·运维·经验分享·jenkins·prometheus
AI Echoes1 小时前
别再手工缝合API了!开源LLMOps神器LMForge,让你像搭积木一样玩转AI智能体!
人工智能·python·langchain·开源·agent
AI Echoes1 小时前
从零构建企业级LLMOps平台:LMForge——支持多模型、可视化编排、知识库与安全审核的全栈解决方案
人工智能·python·langchain·开源·agent
slim~1 小时前
Java基础第9天总结(可变参数、Collections、斗地主)
java·开发语言