Java8 Stream:2万字20个实例,玩转集合的筛选、归约、分组、聚合_云深i不知处的博客-优快云博客
Java8中提供了能够更方便处理集合数据的Stream类,其中parallelStream()方法能够充分利用多核CPU的优势,使用多线程加快对集合数据的处理速度。
@Test
public void test1(){
List<String> strings = new ArrayList<>();
strings.add("张三");
strings.add("李四");
strings.add("王五");
strings.add("赵六");
strings.add("田七");
strings.add("孙八");
ArrayList<String> strings1 = new ArrayList<>();
strings1.add("张三");
strings1.add("王五");
strings1.add("赵六");
// 交集
List<String> intersection = strings.stream().filter(item -> strings1.contains(item)).collect(toList());
System.out.print("交集-->");
intersection.parallelStream().forEach(System.out::print);
System.out.println();
// 差集 (list1 - list2)
List<String> reduce1 = strings.stream().filter(item -> !strings1.contains(item)).collect(toList());
System.out.print("差集(strings - strings1)-->");
reduce1.parallelStream().forEach(System.out::print);
System.out.println();
// 差集 (list2 - list1)
List<String> reduce2 = strings1.stream().filter(item -> !strings.contains(item)).collect(toList());
System.out.print("差集(strings1 - strings)-->");
reduce2.parallelStream().forEach(System.out::print);
System.out.println();
// 并集
List<String> listAll = strings.parallelStream().collect(toList());
List<String> listAll2 = strings1.parallelStream().collect(toList());
listAll.addAll(listAll2);
System.out.print("并集-->");
listAll.parallelStream().forEachOrdered(System.out::print);
System.out.println();
// 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
System.out.print("并集去重-->");
listAllDistinct.parallelStream().forEachOrdered(System.out::print);
}