Stream sorted (Comparator comparator) method in Java
Stream sorted(Comparator comparator) returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. 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. In java 8, Comparator can be instantiated using lambda expression. We can also reverse the natural ordering as well as ordering provided by Comparator.
Stream<T> sorted(Comparator<? super T> comparator) Where, Stream is an interface and T is the type of stream elements. comparator is used to compare stream elements.
Below given are some examples to understand the implementation of the function in a better way.
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.
Example 1 :
The sorted stream according to provided Comparator is : 23 7 5 -10 -18
Example 2 :
The sorted stream according to provided Comparator is : for GeeksforGeeks GeeksQuiz Geeks GFG
Example 3 :
The sorted stream is : GFG for Geeks GeeksforGeeks GeeksQuiz