0

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());
halfer
  • 19,824
  • 17
  • 99
  • 186
H Athukorala
  • 739
  • 11
  • 32
  • 1
    What doesn't work with your above snippet? FYI, `.sorted()` is [_stateful_](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps): "one cannot produce any results from sorting a stream until one has seen all elements of the stream". – sp00m Aug 10 '21 at 17:00
  • 1
    What help do you need? That works. – Louis Wasserman Aug 10 '21 at 17:04

1 Answers1

1

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)

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56