reduce()方法如何与Java 8中的并行流一起使用? [英] How does reduce() method work with parallel streams in Java 8?
问题描述
我尝试了解reduce()
方法如何与并行流完全兼容,并且我不理解为什么以下代码不返回这些字符串的串联.
I try to understand how reduce()
method works exactly with parallel streams and I don't understand why the following code do not return the concatenation of these strings.
这是代码:
public class App {
public static void main(String[] args) {
String[] grades = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"};
StringBuilder concat = Arrays.stream(grades).parallel()
.reduce(new StringBuilder(),
(sb, s) -> sb.append(s),
(sb1, sb2) -> sb1.append(sb2));
System.out.println(concat);
}
}
该代码仅适用于顺序流,但不适用于并行流,它不返回串联.每次输出都不同.有人可以解释一下那里发生了什么吗?
The code works only with sequential streams, but with parallel streams it doesn't return the concatenation. The output is different every time. Can someone explain me what's happening there?
推荐答案
问题是您使用可变的缩减,已 Streams:Reduction 中了解差异.与reduce方法(在处理元素时总是会创建新值)不同,collect方法会修改或变异现有值.
The problem is you use Stream::reduce
for Mutable reduction, which has been Stream::collect
specifically designed for. It can be either used for the safe parallel storing. Read about the differences also at official Oracle documentation Streams: Reduction. Unlike the reduce method, which always creates new value when it processes an element, the collect method modifies or mutates an existing value.
从JavaDoc中注意到这两种方法之间的区别:
Notice the differences between both methods from their JavaDoc:
-
使用提供的标识,累积和组合功能来减少此流的元素.
Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions.
collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)
:对此流的元素执行可变的约简操作.
Performs a mutable reduction operation on the elements of this stream.
因此,我建议您执行以下操作:
Therefore, I suggest you do the following:
StringBuilder concat = Arrays.stream(grades)
.parallel()
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append);
这篇关于reduce()方法如何与Java 8中的并行流一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!