CKTIS / Java
Reverse a comparator with Comparator.reversed()
`Comparator.reversed()` returns a comparator that orders elements in the opposite direction from an existing comparator. The call itself does not sort or change a list.
Version: Java SE 21
Syntax
default Comparator<T> reversed()Comparator.reversed() is a no-argument default method of java.util.Comparator, available since Java 8. Calling c.reversed() returns a Comparator<T> for the same type T without changing c. An element that came before another under c now comes after it, and vice versa. Pairs that compared as 0 still tie.
Use list.sort(c.reversed()) to sort a modifiable list in place with the reversed ordering. List.sort(...) is stable: elements that compare as equal under the supplied comparator keep their relative order. Unlike Comparator.reversed(), the static method Comparator.reverseOrder() reverses the elements' natural order, and List.reversed() gives a view of the list in opposite sequence without comparing elements.
If primary and secondary are comparators, primary.thenComparing(secondary).reversed() reverses both criteria. To reverse only the primary criterion, use primary.reversed().thenComparing(secondary): when the primary criterion produces a tie, the secondary criterion keeps its original direction.
Examples
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("plum", "fig", "pear", "banana"));
Comparator<String> byLength = Comparator.comparingInt(String::length);
words.sort(byLength.reversed());
System.out.println(words);
}
}Result
[banana, plum, pear, fig]
`Comparator.comparingInt(String::length)` compares strings from shortest to longest. With that ordering reversed, `banana` comes first and `fig` comes last. `plum` and `pear` have the same length, so `plum` still comes before `pear`.
Related lessons
- Java · Lesson 48 · Basic · Version: 2
Sources
- Comparator (Java SE 21 & JDK 21) — reversed()
- Comparator (Java SE 21 & JDK 21) — reverseOrder()
- Comparator (Java SE 21 & JDK 21) — thenComparing(Comparator)
- Comparator (Java SE 21 & JDK 21) — comparingInt(ToIntFunction)
- List (Java SE 21 & JDK 21) — sort(Comparator)
- List (Java SE 21 & JDK 21) — reversed()