Stream sorted() in Java
Stream 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. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements.
Stream<T> sorted() Where, Stream is an interface and T is the type of stream elements.
Exception : If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.
Below given are some examples to understand the implementation of the function in a better way.
Example 1 :
The sorted stream is : -18 -9 0 4 25
Example 2 :
The sorted stream is : GFG Geeks GeeksQuiz GeeksforGeeks for
Example 3 :
1, 100 5, 10 10, 20 50, 2000
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.