I am trying to understand reduce method. If I use reduce with stream() I get _ab and if I use reduce with parallelStream() I get _a_b. 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()
.peek(TestParallelStream::sleepFor)
.reduce("_",(a,b) -> a.concat(b));
System.out.println(join);
}
public static void sleepFor(String w){
System.out.println("inside thread:"+w);
try{
Thread.currentThread().sleep(5000);
}catch(InterruptedException e){ }
}
}
It would be, if you had passed valid arguments. Read the Javadoc:
The
identityvalue must be an identity for the accumulator function. This means that for allt,accumulator.apply(identity, t)is equal tot.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With