Java – How does sorting with java 8 stream work under the hood

javajava8stream-processing

When I call Stream.sort(..) is there a new array of elements created and the stream iterates over the newly created sorted array?

In other words, how Java 8 Stream does sort under the hood?

Best Answer

You can use grepcode.com to search through the Java standard library code (and some other libraries). Unfortunately, the stream implementation code is rather abstract. A good starting point is the internal java.util.stream.SortedOps class which transforms a stream into a sorted stream.

The current implementation (used for streams of standard library containers) makes it a no-op if the stream is already sorted, uses an array if the size of the stream is known (SizedRefSortingSink), or accumulates all elements in an ArrayList if the size is unknown (RefSortingSink).

Of course, such implementation details may change with any release, but the fundamental considerations are universal: Sorting a stream is necessarily an eager/blocking operation, and sorting an infinite stream is not meaningful. This means sorting a stream is not useful if you use streams because they can be lazy, but you still get the convenient stream syntax.

Other streams will have to provide their own implementation of Stream.sorted(), which will likely be similar.

Related Topic