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 and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Character Stream Vs Byte Stream in Java
- Difference between Stream.of() and Arrays.stream() method in Java
- foreach() loop vs Stream foreach() vs Parallel Stream foreach()
- Stream sorted (Comparator comparator) method in Java
- Java Stream | Collectors toCollection() in Java
- Stream In Java
- java.util.stream.IntStream/LongStream | Search an element
- stream.limit() method in Java
- Stream skip() method in Java with examples
- Stream.reduce() in Java with examples
- Stream.concat() in Java
- Stream.distinct() in Java
- Stream.max() method in Java with Examples
- Stream min() method in Java with Examples
- Stream generate() method in Java with examples
- Stream count() method in Java with examples
- Stream.of(T... values) in Java with examples
- Stream.of(T t) in Java with examples
- Stream peek() in Java with examples
- Stream map() in Java with examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.