Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 reduce with parallelStream and stream [duplicate]

Tags:

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){ }
    }
}
like image 522
puvi Avatar asked Apr 29 '16 20:04

puvi


1 Answers

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.

like image 194
Louis Wasserman Avatar answered Sep 28 '22 03:09

Louis Wasserman