一 根据数据量,合理使用并行流
并行有线程上下文切换的损耗,如果集合内容不大,使用串行更佳.
1.使用parallel()
private static void test01() { Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0); //创建一个普通流 System.out.println(integerStream.isParallel()); //打印流是否是并行流 Optional<Integer> sumOptional = integerStream.parallel() //将串行流设置为并行流 .peek((num) -> { System.out.println(num + ":" + Thread.currentThread().getName()); //打印数字和线程名字,验证是否是多线程 }) .filter(num -> num > 6) //过滤,保留大于6的元素 .reduce((n1, n2) -> n1 + n2); //求和 sumOptional.ifPresent(System.out::println); //如果结果存在,打印 }
false 7:main 8:ForkJoinPool.commonPool-worker-4 3:ForkJoinPool.commonPool-worker-9 6:main 0:ForkJoinPool.commonPool-worker-13 2:ForkJoinPool.commonPool-worker-11 1:ForkJoinPool.commonPool-worker-6 4:ForkJoinPool.commonPool-worker-9 5:ForkJoinPool.commonPool-worker-4 9:ForkJoinPool.commonPool-worker-2 24
2.使用parallelStream()
private static void test02() { Integer[] arr={1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; List<Integer> integers = Arrays.asList(arr); Optional<Integer> sumOptional =integers.parallelStream() //创建并行流 .peek((num) -> { System.out.println(num + ":" + Thread.currentThread().getName()); //打印数字和线程名字,验证是否是多线程 }) .filter(num -> num > 6) //过滤,保留大于6的元素 .reduce((n1, n2) -> n1 + n2); //求和 sumOptional.ifPresent(System.out::println); //如果结果存在,打印 }
7:main 3:ForkJoinPool.commonPool-worker-9 0:ForkJoinPool.commonPool-worker-13 1:ForkJoinPool.commonPool-worker-6 4:ForkJoinPool.commonPool-worker-13 9:ForkJoinPool.commonPool-worker-2 6:main 8:ForkJoinPool.commonPool-worker-4 2:ForkJoinPool.commonPool-worker-11 5:ForkJoinPool.commonPool-worker-9 24
二 基本类型的优化
private static void test03() { Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0); //创建一个普通流 System.out.println(integerStream.isParallel()); //打印流是否是并行流 OptionalInt reduce = integerStream.parallel() //将串行流设置为并行流 .peek((num) -> { System.out.println(num + ":" + Thread.currentThread().getName()); //打印数字和线程名字,验证是否是多线程 }) .mapToInt(new ToIntFunction<Integer>() { @Override public int applyAsInt(Integer value) { return value; } }) .filter(num -> num > 6) //过滤,保留大于6的元素 .reduce((n1, n2) -> n1 + n2);//求和 int asInt = reduce.getAsInt(); System.out.println(asInt); }
集合元素为Integer类型,过滤计算使用int基本类型,如果数据量比较大,会涉大量自动拆箱装箱.我们可以直接使用mapToInt装换为基本类型进行操作,减少拆装箱.
使用map和flatMap时,更具需求,可以考虑使用基本类型.