java8 两个List集合取交集、并集、差集

List reduceList =
        sdDrugHospitalNewEntities.stream().filter(item ->
                !baseHospitalOrganizationEntities.stream().map(e ->                     e.getHospitalName()).collect(Collectors.toList()).contains(item.getHospitalName())).collect(Collectors.toList());

将两个list根据某个属性进行合并
List> list1 = new ArrayList();
List> list2 = new ArrayList();
list1.stream().map(m -> {
    list2 .stream().filter(item -> Objects.equals(m.get("userId"), item.get("userId"))).forEach(item -> {
        m.put("userName", item.get("userName"));
        m.put("age", item.get("age"));
    });
    return m;
}).collect(Collectors.toList());


public static void main(String[] args) {
    List list1 = new ArrayList();
    list1.add("1");
    list1.add("2");
    list1.add("3");
    list1.add("5");
    list1.add("6");
 
    List list2 = new ArrayList();
    list2.add("2");
    list2.add("3");
    list2.add("7");
    list2.add("8");
 
    // 交集
    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);

    // 并集
    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);
 
    System.out.println("---原来的List1---");
    list1.parallelStream().forEachOrdered(System.out :: println);
    System.out.println("---原来的List2---");
    list2.parallelStream().forEachOrdered(System.out :: println);
 
}


 
  

你可能感兴趣的:(servlet,java,服务器)