Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream reduce vs Stream.parallel.reduce() [duplicate]

I'm trying to understand why the result of this example is always true here's my example :

 String s1 = Arrays.asList("A", "E", "I", "O", "U").stream()
                .reduce("", String::concat);
 String s2 = Arrays.asList("A", "E", "I", "O", "U").parallelStream()
                .reduce("", String::concat);

System.out.println(s1.equals(s2));

This always print true , what I know is with the parallelStream we can't predict the results can someone explain why?

like image 396
e2rabi Avatar asked Dec 14 '22 10:12

e2rabi


1 Answers

If you take a look at the docs of Stream.reduce() you will find this:

Performs a reduction on the elements of this stream [...] and returns the reduced value. This is equivalent to:

 T result = identity;
 for (T element : this stream)
     result = accumulator.apply(result, element)
 return result;

but is not constrained to execute sequentially.

So Stream.reduce() ensures the values are processed in order.

If you try using Stream.forEach() and print each value like this:

Arrays.asList("A", "E", "I", "O", "U").stream()
        .forEach(System.out::print);
System.out.println();
Arrays.asList("A", "E", "I", "O", "U").parallelStream()
        .forEach(System.out::print);

You will get this result (or something similar in the second line):

AEIOU
IUOEA

(Stream.forEachOrdered() with the example above will also print the values in order)

like image 187
Samuel Philipp Avatar answered Jan 01 '23 18:01

Samuel Philipp