VOOZH about

URL: https://www.geeksforgeeks.org/java/stream-sorted-in-java/

⇱ Stream sorted() in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Stream sorted() in Java

Last Updated : 23 Jan, 2026

Stream.sorted() is an intermediate, stateful operation that returns a stream with elements sorted in natural order or by a given Comparator. It is stable for ordered streams, requires elements to be Comparable (or a comparator), and may throw ClassCastException if elements are not comparable.

Example:


Output
-18
-9
0
4
25

Explanation:

  • list.stream() converts the list into a stream.
  • sorted() arranges elements in their natural (ascending) order.
  • forEach() prints each sorted element.

Syntax

Stream<T> sorted()

  • Paramerter: "T" type of stream elements.

Example 1: This code demonstrates how Stream.sorted() sorts elements of a stream in natural order without modifying the original collection.


Output
Geeks
Geeks
Welcome
You
for

Explanation:

  • .sorted() sorts the stream elements in their natural order (alphabetically for strings).
  • The original list remains unchanged; only the stream is sorted.

Example 2: This code demonstrates sorting a stream of Point objects by their x coordinate using Stream.sorted() with a custom comparator.


Output
1, 100
5, 10
10, 20
50, 2000

Explanation:

  • .sorted((p1, p2) -> p1.x.compareTo(p2.x)) sorts the points based on their x coordinate.
  • Sorting is stable; the original list is not modified.
Comment