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
- Stream sorted (Comparator comparator) method in Java
- Difference between Stream.of() and Arrays.stream() method in Java
- Character Stream Vs Byte Stream in Java
- Java Stream | Collectors toCollection() in Java
- Java 8 Stream
- Stream In Java
- Convert a Set to Stream in Java
- Convert Stream to Set in Java
- Stream map() in Java with examples
- Stream of() method in Java
- Array to Stream in Java
- Stream.of(T t) in Java with examples
- Stream.concat() in Java
- How to get Slice of a Stream in Java
- Stream.distinct() in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.