Stream.sorted()
Sorts the elements of a stream.
Available since: Java 8
Syntax
Stream<T> sorted()
Stream<T> sorted(Comparator<? super T> comparator)Parameters
| Parameter | Type | Description |
|---|---|---|
| comparator | Comparator<? super T> | Optional comparison rule. |
Return value
Stream<T>A sorted stream.
Examples
A sorted copy; the source list stays the same:
void main() {
List<Integer> nums = List.of(3, 1, 2);
IO.println(nums.stream().sorted().toList());
IO.println(nums.stream().sorted(Comparator.reverseOrder()).toList());
IO.println(nums);
}Output:
[1, 2, 3]
[3, 2, 1]
[3, 1, 2]The three most expensive products:
record Product(String name, int price) {}
void main() {
var products = List.of(new Product("a", 50), new Product("b", 10),
new Product("c", 90), new Product("d", 70));
products.stream()
.sorted(Comparator.comparingInt(Product::price).reversed())
.limit(3)
.forEach(p -> IO.println(p.name() + " " + p.price()));
}Output:
c 90
d 70
a 50Notes
Without an argument the elements must be Comparable, otherwise a ClassCastException occurs at run time. The sort is stable for ordered streams. It is a heavy operation that must see all elements, so it never finishes on an infinite stream.
See also
- List.sort() — Sorts a list in place using a given rule.
- Comparator.comparing() — Creates a comparator that compares objects by one key.
- Stream.distinct() — Removes duplicate elements from a stream.
In the tutorial
- Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.