【问题标题】:Accumulator on parallel stream reduction is always called only with identity并行流减少的累加器始终仅以身份调用
【发布时间】: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


    【解决方案1】:

    该示例正在处理一个小型数据集。我们需要有很多元素才能看到这种行为(也取决于运行代码的机器的容量)。

    例如,创建 100 个字符串并运行它,我可以看到 Accumulator called with 1 and a 打印出来。

    元素个数越多,累加器被重复调用累加的次数就越多。

    【讨论】:

      猜你喜欢
      • 2014-12-16
      • 2018-03-05
      • 2020-05-01
      • 2015-06-04
      • 2018-01-23
      • 2018-08-05
      • 2019-03-03
      • 2022-01-08
      • 2018-10-18
      相关资源
      最近更新 更多