Java8 streams sequential and parallel execution produce different results?

前端 未结 3 1704
逝去的感伤
逝去的感伤 2020-12-05 06:17

Running the following stream example in Java8:

    System.out.println(Stream
        .of(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\")
        .reduce(\"\", (s1,         


        
3条回答
  •  攒了一身酷
    2020-12-05 07:09

    To add to other answer,

    You might want to use Mutable reduction, the doc specify that doing something like

    String concatenated = strings.reduce("", String::concat)
    

    Will give bad performance result.

    We would get the desired result, and it would even work in parallel. However, we might not be happy about the performance! Such an implementation would do a great deal of string copying, and the run time would be O(n^2) in the number of characters. A more performant approach would be to accumulate the results into a StringBuilder, which is a mutable container for accumulating strings. We can use the same technique to parallelize mutable reduction as we do with ordinary reduction.

    So you should use a StringBuilder instead.

提交回复
热议问题