Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Comparator.reversed()

Returns a comparator with the opposite order. For the natural order there is Comparator.reverseOrder().

Available since: Java 8

Syntax

default Comparator<T> reversed()

Return value

Comparator<T>A new comparator that sorts the other way.

Examples

Descending by price, and strings in descending order:

record Item(String name, int price) {}
 
void main() {
    var items = new ArrayList<>(List.of(new Item("pen", 2), new Item("book", 15), new Item("bag", 40)));
    items.sort(Comparator.comparingInt(Item::price).reversed());
    IO.println(items.getFirst().name());
 
    var words = new ArrayList<>(List.of("b", "c", "a"));
    words.sort(Comparator.reverseOrder());
    IO.println(words);
}

Output:

bag
[c, b, a]

Notes

reversed() reverses the whole chain it is applied to: comparing(A).thenComparing(B).reversed() reverses both criteria. With an untyped lambda, comparing(p -> p.price()).reversed() does not compile — the compiler cannot infer the type of p; use a method reference or state the type: (Item p) -> p.price().

See also

Related recipes

In the tutorial

  • Sorting and comparators — Sorting collections in Java: natural order, reverse order, the Comparable interface, Comparator.comparing and sorting by several fields.

Thanks for reading!

Donate to the site — we work hard for you.