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);
    }
    }
相关推荐
木卯1 分钟前
5种创建型设计模式笔记(Python实现)
python·设计模式
小五Z4 分钟前
RabbitMQ高级特性--消息确认机制
java·rabbitmq·intellij-idea
Kevinyu_15 分钟前
Maven
java·maven
张琪杭18 分钟前
pytorch tensor创建tensor
人工智能·pytorch·python
nickxhuang20 分钟前
【基础知识】回头看Maven基础
java·maven
shylyly_22 分钟前
list的模拟实现
数据结构·c++·链表·迭代器·list·list的模拟实现
星星点点洲28 分钟前
【RAG】RAG 系统的基本搭建流程(ES关键词检索示例)
python·elasticsearch
带娃的IT创业者1 小时前
《Python实战进阶》No18: 使用 Apache Spark 进行分布式计算
python·spark·apache
日月星辰Ace1 小时前
jwk-set-uri
java·后端
Tomorrow'sThinker1 小时前
Python零基础学习第三天:函数与数据结构
开发语言·windows·python