Stream reduce vs Stream.parallel.reduce()

e2rabi :

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?

Samuel Philipp :

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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=305088&siteId=1