einer der Sucher einer der Sucher - 5 months ago 9
Java Question

java 8 reduce with parallelStream and stream

I am trying to understand reduce method. If I use reduce with stream() I get

and if I use reduce with
I get
. Should not the output of reduce be same whether we use parallelStream or stream?

import java.util.*;
import java.util.stream.*;

class TestParallelStream{

public static void main(String args[]){
List<String> l = Arrays.asList("a","b","c","d");
String join=l.stream()
.reduce("_",(a,b) -> a.concat(b));

public static void sleepFor(String w){
System.out.println("inside thread:"+w);
}catch(InterruptedException e){ }


It would be, if you had passed valid arguments. Read the Javadoc:

The identity value must be an identity for the accumulator function. This means that for all t, accumulator.apply(identity, t) is equal to t.

This is not the case for the inputs you've passed; "_".concat(t) is not equal to t. Since you've passed invalid arguments, the behavior of the method is undefined and the method is allowed to do anything, including making demons shoot out of your nose.

I have a hard time telling the behavior you actually want, though I suspect you want .collect(joining("_")). You haven't actually told us your desired output, though.