Does anyone know what the time complexity of java.util.stream.Stream<T>.sorted()
is?
It is O(n) . The stream filtering uses iteration internally. But, that conversion process is also O(n).
Stream sorted() in JavaStream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed.
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Java Stream sorted() Learn to use Stream sorted() method to sort the elements in a Stream by their natural order.
Well, sorted()
in itself is O(1), since it's an intermediate operation that doesn't consume the stream, but simply adds an operation to the pipeline.
Once the stream is consumed by a terminal operation, the sort happens and either
Arrays.sort()
(O(n log n))Arrays.parallelSort()
(O(n log n))As of JDK 8, the main sorting algorithm which is also used in standard stream API implementation for sequential sorting is TimSort. Its worst case is O(n log n)
, but it works incredibly fast (with O(n)
and quite small constant) if data is presorted (in forward or reverse direction) or partially presorted (for example, if you concatenate two sorted lists and sort them again).
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