Is there a way to sort a list using parallelStream()
? I saw there are forEach
and forEachOrdered
. But I was checking if there is a way to sort as follows,
list.parallelStream().map().sorted().collect(Collectors.toList());
Is there a way to sort a list using parallelStream()
? I saw there are forEach
and forEachOrdered
. But I was checking if there is a way to sort as follows,
list.parallelStream().map().sorted().collect(Collectors.toList());
A parallel stream is just a standard stream, so it is possible to apply sorted
to a parallel stream. The result of the sorted
method is a sequential stream.
So it works as follow:
list.parallelStream() // Generate a parallel stream
.map(item -> ...) // Item are mapped in parallel
.sorted() // sorted needs to wait for all elements before continuing
// Here the stream is sequential
.collect(Collectors.toList()); // Collect to a new list
So sorted can operates on a parallel stream, but the resulting stream is sequential and it is released only after all elements of the parallel stream are received.
Updated answer (thanks to @Louis Wasserman)
The result of sorted is not sequential. The terminal operation will maintain the same order of the original stream not depending on if it is a sequential stream or a parallel stream. So the correct code exposed before must be changed in the comments as below
list.parallelStream() // Generate a parallel stream
.map(item -> ...) // Item are mapped in parallel
.sorted() // sorted needs to wait for all elements before continuing
// REMOVED --> Here the stream is sequential
.collect(Collectors.toList()); // Collect to a new list
// ADDED --> in the same order of the received after the sorted step
If you add a map operation after the sorted with a random executing time you can see that this map operation can end in different moments, but at the end the collect will generate a List in the original order. (thanks to Louis Wasserman... I did a mistake I was not knowing the real internal details of stream, I hope that the updated answer give you the ability to better understand how streams works)