Card 08/ 09

ExerciseDifficulty: Advanced1 min

Practice: Predicting the Order Four Comparator Chains Produce

The same three pieces in a different order give a different result, because of reversed().

In a comparator chain, thenComparing only acts on ties, and reversed() reverses everything to its left. Apply those two rules to the four comparators below, over the same three people, and write down the order each produces before opening the answer.

java
record Person(String name, int age) { }

List<Person> people = new ArrayList<>(List.of(
    new Person("Ada", 36),
    new Person("Bea", 28),
    new Person("Cal", 36)));
java
// 1
Comparator.comparingInt(Person::age)
// 2
Comparator.comparingInt(Person::age).reversed()
// 3
Comparator.comparingInt(Person::age).thenComparing(Person::name).reversed()
// 4
Comparator.comparingInt(Person::age).reversed().thenComparing(Person::name)
The four orders, and what reversed() applied to in each
Each chain, the order it produces, and what was reversed
Orderreversed() applied to
1Bea, Ada, CalNothing
2Ada, Cal, BeaThe whole comparator; the two 36s tie and keep their list order
3Cal, Ada, BeaThe whole chain, including the name tie-break
4Ada, Cal, BeaThe age only; names then break the tie in ascending order

Chains three and four contain the same three pieces and produce different orders. reversed() applies to everything to its left, so where you put it decides how much it reverses.

The second row relies on Java's sort being stable, which means tied elements stay in the order they were in. That happens to give Ada before Cal here; relying on it is a decision better made explicitly, by adding a tie-break.