gpt4 book ai didi

java - Stream reduce vs Stream.parallel.reduce()

转载 作者:行者123 更新时间:2023-12-03 21:43:21 32 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What do the Stream reduce() requirements exactly entail?

(4 个回答)


1年前关闭。




我试图理解为什么这个例子的结果总是如此,这是我的例子:

 String s1 = Arrays.asList("A", "E", "I", "O", "U").stream()
.reduce("", String::concat);
String s2 = Arrays.asList("A", "E", "I", "O", "U").parallelStream()
.reduce("", String::concat);

System.out.println(s1.equals(s2));

这总是打印 true ,我所知道的是对于 parallelStream 我们无法预测结果有人可以解释为什么吗?

最佳答案

如果您查看 Stream.reduce() 的文档你会发现:

Performs a reduction on the elements of this stream [...] and returns the reduced value. This is equivalent to:

 T result = identity;
for (T element : this stream)
result = accumulator.apply(result, element)
return result;

but is not constrained to execute sequentially.



所以Stream.reduce()确保按顺序处理值。

如果您尝试使用 Stream.forEach()并像这样打印每个值:
Arrays.asList("A", "E", "I", "O", "U").stream()
.forEach(System.out::print);
System.out.println();
Arrays.asList("A", "E", "I", "O", "U").parallelStream()
.forEach(System.out::print);

您将得到以下结果(或第二行中的类似结果):
AEIOU
IUOEA

( Stream.forEachOrdered() 上面的例子也将按顺序打印值)

关于java - Stream reduce vs Stream.parallel.reduce(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58468225/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com