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

半城伤御伤魂 提交于 2019-12-02 08:41:58

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:

Therefore, I suggest you do the following:

StringBuilder concat = Arrays.stream(grades)
    .parallel()
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!