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?
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)
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