Java 25 (LTS) reference · Stream API
Java Stream sorted() Method
Return a stream sorted by natural order or by a Comparator. The source collection is not changed.
Java 25 (LTS) Since Java 8
Syntax
stream.sorted(comparator)
Parameters
| Parameter | Description |
|---|---|
comparator optionalComparator<T> |
Optional ordering. |
Return value
A new sorted Stream<T>.
Examples
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(5, 2, 9);
System.out.println(nums.stream().sorted().toList());
System.out.println(nums.stream().sorted(Comparator.reverseOrder()).toList());
System.out.println(nums);
}
}
Output
[2, 5, 9] [9, 5, 2] [5, 2, 9]
Run this on your computer — see “Get Started” for setup.
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
System.out.println(Stream.of("kettle", "tea", "mug").sorted(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder())).toList());
}
}
Output
[mug, tea, kettle]
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
list.sort()· Sort a list in place with a Comparator, or by natural order when you pass null. Collections.sort() does the same.stream.distinct()· Remove duplicate elements (by equals()), keeping the first occurrence of each, in encounter order.- Java Streams · tutorial