【发布时间】:2022-08-21 14:36:58
【问题描述】:
我正在使用 Stream#reduce 的三参数版本。从字符串列表开始,0 作为身份, 这累加器添加字符串的标识和长度。这合路器添加两个部分结果。
List<String> strings = new ArrayList<>();
IntStream.range(0, 10)
.forEach(i -> strings.add(\"a\"));
System.out.println(strings.stream()
.parallel()
.reduce(0,
(res, s) -> {
System.out.println(\"Accumulator called with \" + res + \" and \" + s);
return res + s.length();
},
(a, b) -> {
System.out.println(\"Combiner called with \" + a + \" and \" + b);
return a + b;
}));
运行此Accumulator called with 0 and a 时会打印 10 次,而会发生部分结果的总和只要在组合器中,
Combiner called with 1 and 1
Combiner called with 1 and 2
....
Combiner called with 2 and 3
Combiner called with 5 and 5
为什么不使用先前(非身份)结果和字符串调用累加器,即为什么我们看不到像Accumulator called with 1 and a 这样的打印语句?
标签: java java-stream