jdk 8 交集 差集
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { List<String> list1 = new ArrayList<String>(); list1.add("1"); list1.add("2"); list1.add("3"); list1.add("5"); list1.add("6"); List<String> list2 = new ArrayList<String>(); list2.add("2"); list2.add("3"); list2.add("7"); list2.add("8"); // 交集 2,3 List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList()); System.out.println("---交集 intersection---"); intersection.parallelStream().forEach(System.out :: println); // 差集 (list1 - list2) // List<WmSoDetail> chajiDetails = wmSoDetailList.stream() // .filter(item -> !upWmSoDetailList.stream() // .map(e -> e.getJobId()) // .collect(Collectors.toList()) // .contains(item.getJobId())) // .collect(Collectors.toList()); List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.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(Collectors.toList()); System.out.println("---差集 reduce2 (list2 - list1)---"); reduce2.parallelStream().forEach(System.out :: println); // 并集 123562378 List<String> listAll = list1.parallelStream().collect(Collectors.toList()); List<String> listAll2 = list2.parallelStream().collect(Collectors.toList()); listAll.addAll(listAll2); System.out.println("---并集 listAll---"); listAll.parallelStream().forEachOrdered(System.out :: println); // 去重并集 1235678 List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.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); } }
list1:12356
list2:2378
---交集 intersection--- 3 2 ---差集 reduce1 (list1 - list2)--- 5 6 1 ---差集 reduce2 (list2 - list1)--- 8 7 ---并集 listAll--- 1 2 3 5 6 2 3 7 8 ---得到去重并集 listAllDistinct--- 1 2 3 5 6 7 8 ---原来的List1--- 1 2 3 5 6 ---原来的List2--- 2 3 7 8
来源:https://blog.csdn.net/Dhjie_king/article/details/103169427