Parallel Stream behaving differently to Stream

Claudiga :

I am having trouble comprehending why parallel stream and stream are giving a different result for the exact same statement.

    List<String> list = Arrays.asList("1", "2", "3");
    String resultParallel = list.parallelStream().collect(StringBuilder::new,
            (response, element) -> response.append(" ").append(element),
            (response1, response2) -> response1.append(",").append(response2.toString()))
            .toString();
    System.out.println("ResultParallel: " + resultParallel);

    String result = list.stream().collect(StringBuilder::new,
            (response, element) -> response.append(" ").append(element),
            (response1, response2) -> response1.append(",").append(response2.toString()))
            .toString();

    System.out.println("Result: " + result);

ResultParallel: 1, 2, 3

Result: 1 2 3

Can somebody explain why this is happening and how I get the non-parallel version to give the same result as the parallel version?

Eugene :

As a side note, even if you replace , with a space in the combiner, your results are still going to differ (slightly altered the code to make it more readable):

String resultParallel = list.parallelStream().collect(
            StringBuilder::new,
            (builder, elem) -> builder.append(" ").append(elem),
            (left, right) -> left.append(" ").append(right)).toString();

    String result = list.stream().collect(
            StringBuilder::new,
            (builder, elem) -> builder.append(" ").append(elem),
            (left, right) -> left.append(" ").append(right)).toString();


  System.out.println("ResultParallel: ->" + resultParallel + "<-"); // -> 1  2  3  4<-
  System.out.println("Result: ->" + result + "<-"); // -> 1 2 3 4<-

Notice how you have a little too many spaces.

The java-doc has the hint:

combiner... must be compatible with the accumulator function

If you want to join, there are simpler options like:

String.join(",", yourList)
yourList.stream().collect(Collectors.joining(","))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35755&siteId=1