Card 08/ 09
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.
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)));// 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
| Order | reversed() applied to | |
|---|---|---|
| 1 | Bea, Ada, Cal | Nothing |
| 2 | Ada, Cal, Bea | The whole comparator; the two 36s tie and keep their list order |
| 3 | Cal, Ada, Bea | The whole chain, including the name tie-break |
| 4 | Ada, Cal, Bea | The 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.
← → move through sections and cards