Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Stream.sorted()

Sorts the elements of a stream.

Available since: Java 8

Syntax

Stream<T> sorted()
Stream<T> sorted(Comparator<? super T> comparator)

Parameters

ParameterTypeDescription
comparatorComparator<? 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 50

Notes

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

In the tutorial

  • Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.

Thanks for reading!

Donate to the site — we work hard for you.