zoukankan      html  css  js  c++  java
  • java中list集合的操作(交集,并集,差集)

    import static java.util.stream.Collectors.toList;
    import java.util.ArrayList;
    import java.util.List;
    /**
    * @ClassName: T
    * @Author: boss
    * @Date: 2020-01-04
    * @Description: list集合的操作(交集,并集,差集)
    */
    public class T {

    public static void main(String[] args) {
    List<String> list1 = new ArrayList();
    list1.add("1111");
    list1.add("2222");
    list1.add("3333");

    List<String> list2 = new ArrayList();
    list2.add("3333");
    list2.add("4444");
    list2.add("5555");

    // 交集
    List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
    System.out.println("---得到交集 intersection---");
    intersection.parallelStream().forEach(System.out :: println);

    // 差集 (list1 - list2)
    List<String> 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<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());
    System.out.println("---得到差集 reduce2 (list2 - list1)---");
    reduce2.parallelStream().forEach(System.out :: println);

    // 并集
    List<String> listAll = list1.parallelStream().collect(toList());
    List<String> listAll2 = list2.parallelStream().collect(toList());
    listAll.addAll(listAll2);
    System.out.println("---得到并集 listAll---");
    listAll.parallelStream().forEach(System.out :: println);

    // 去重并集
    List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
    System.out.println("---得到去重并集 listAllDistinct---");
    listAllDistinct.parallelStream().forEach(System.out :: println);

    System.out.println("---原来的List1---");
    list1.parallelStream().forEach(System.out :: println);
    System.out.println("---原来的List2---");
    list2.parallelStream().forEach(System.out :: println);

    // 一般有filter 操作时,不用并行流parallelStream ,如果用的话可能会导致线程安全问题
    }
    }

  • 相关阅读:
    UVa 11538 Chess Queen (排列组合计数)
    CodeForces 730H Delete Them (暴力)
    CodeForces 730G Car Repair Shop (暴力)
    汇编(assembling)简介(源:阮一峰)
    CSS骚操作
    Jquery复习总结
    CGI与ISAPI的区别(转)
    SQL中Group By的使用(转)
    05 ADO.net
    04 SqlServer
  • 原文地址:https://www.cnblogs.com/kelelipeng/p/15573211.html
Copyright © 2011-2022 走看看