I am working on java 8 parallel stream and wanting to print the elements in parallel stream is some order (say insertion order, reverse order or sequential order).
For which i tried the following code:
System.out.println("With forEachOrdered:");
listOfIntegers
.parallelStream()
.forEachOrdered(e -> System.out.print(e + " "));
System.out.println("");
System.out.println("With Sequential:");
listOfIntegers.parallelStream()
.sequential()
.forEach(e -> System.out.print(e + " "));
And for both of these, i got the same output as follows:
With forEachOrdered:
1 2 3 4 5 6 7 8
With Sequential:
1 2 3 4 5 6 7 8
from the api documentation, i can see that:
forEachOrdered -> This is a terminal operation.
and
sequential -> This is an intermediate operation.
So my question is which one is more better to use? and in which scenarios, one should be preferred over other?
listOfIntegers.parallelStream().sequential().forEach()
creates a parallel Stream
and then converts it to a sequential Stream
, so you might as well use listOfIntegers.stream().forEach()
instead, and get a sequential Stream
in the first place.
listOfIntegers.parallelStream().forEachOrdered(e -> System.out.print(e + " "))
performs the operation on a parallel Stream
, but guarantees the elements will be consumed in the encounter order of the Stream
(if the Stream
has a defined encounter order). However, it can be executed on multiple threads.
I don't see a reason of ever using listOfIntegers.parallelStream().sequential()
. If you want a sequential Stream
, why create a parallel Stream
first?