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:
import java.util.*;
class GFG {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4);
list.stream().sorted().forEach(System.out::println);
}
}
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.
import java.util.*;
class GFG {
public static void main(String[] args) {
List<String> list = Arrays.asList("Geeks", "for", "Geeks", "Welcome", "You");
list.stream().sorted().forEach(System.out::println);
}
}
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.
import java.util.*;
class Point {
Integer x, y;
Point(Integer x, Integer y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + ", " + y;
}
}
class GFG {
public static void main(String[] args) {
List<Point> list = Arrays.asList(
new Point(10, 20),
new Point(5, 10),
new Point(1, 100),
new Point(50, 2000)
);
list.stream()
.sorted((p1, p2) -> p1.x.compareTo(p2.x))
.forEach(System.out::println);
}
}
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.