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

前端 未结 1 1015
借酒劲吻你
借酒劲吻你 2021-01-20 11:48

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 th

相关标签:
1条回答
  • 2021-01-20 12:16

    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);
    
    0 讨论(0)
提交回复
热议问题