java8 reduce方法三个参数情况下的理解和示例
2022/3/2 14:16:43
本文主要是介绍java8 reduce方法三个参数情况下的理解和示例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
<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]
这篇关于java8 reduce方法三个参数情况下的理解和示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现
- 2024-05-30我们小公司,哪像华为一样,用得上IPD(集成产品开发)?