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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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 Stream to Set in Java
- Stream of() method in Java
- Stream.concat() in Java
- Convert a Set to Stream in Java
- Array to Stream in Java
- Stream map() in Java with examples
- Stream.of(T t) in Java with examples
- How to get Slice of a Stream in Java
- Stream.distinct() in Java
- How to convert a Stream into a Map in Java
- How to get ArrayList from Stream in Java 8
- Stream.Builder build() in Java
- Stream.max() method in Java with Examples
- Find the last element of a Stream 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 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.