<U> U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator<U> combiner)
在串行流(stream)中,第三个参数combiner不会起作用。
在并行流(parallelStream)中,流被fork join出多个线程进行执行,此时每个线程的执行流程就跟第二个方法reduce(identity, accumulator)一样,而第三个参数combiner函数,则是将每个线程的执行结果当成一个新的流,然后使用第一个方法reduce(accumulator)流程进行规约。
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); // 示例1 System.out.println( numbers.stream().reduce(100, (x,y)-> x = x+y, (x,y)-> x = x+y) ); System.out.println( numbers.parallelStream().reduce(100, (x,y)-> x = x+y, (x,y)-> x = x+y) ); //115 //515 // 示例2 List<Integer> list = new ArrayList<>(); list.add(100); System.out.println( numbers.stream().reduce(list, (x,y)-> {List<Integer> ll = new ArrayList<>(x);ll.add(y); return ll;}, (x,y)-> {List<Integer> ll = new ArrayList<>(x);ll.addAll(y); return ll;}) ); System.out.println( numbers.parallelStream().reduce(list, (x,y)-> {List<Integer> ll = new ArrayList<>(x);ll.add(y); return ll;}, (x,y)-> {List<Integer> ll = new ArrayList<>(x);ll.addAll(y); return ll;}) ); //[100, 1, 2, 3, 4, 5] //[100, 1, 100, 2, 100, 3, 100, 4, 100, 5]