Parallel Stream returns a different than Stream

  • A+
Category:Languages

I am having trouble comprehending why parallel stream and stream are returning different 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 do i get the non parallel version to give the result of the parallel?

 


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(",")) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: