How does reduce() method work with parallel streams in Java 8?

懵懂的女人 提交于 2019-12-02 21:59:56

问题


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.

This is the code:

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?


回答1:


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.

Notice the differences between both methods from their JavaDoc:

  • reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner):

    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);


来源:https://stackoverflow.com/questions/56023452/how-does-reduce-method-work-with-parallel-streams-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!