java8 reduce方法三个参数情况下的理解和示例
<U> U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator<U> combiner)在串行流(stream)中,第三个参数combiner不会起作用。在并行流(parallelStream)中,流被fork join出多个线程进行执行,此时每个线程的执行流程就跟第二
·
<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(Integer::sum).get() ); System.out.println( numbers.stream().reduce(100, Integer::sum) ); 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) ); //15 //115 //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]

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)