Card 08/ 09

ExerciseDifficulty: Advanced1 min

Four Chains: Write Down the Order Each Produces

Four comparators over the same three people. Write down the order each produces before opening the reveal.

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, Bea — or Cal, Ada, BeaThe whole comparator; the two 36s still tie
3Cal, Ada, BeaThe whole chain, including the name tie-break
4Ada, Cal, BeaThe age only; names then break the tie ascending

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 has two answers and that is the finding. With no tie-break the two 36s are in whatever order the sort left them — which for Java's sort means the order they were in, because it is stable. Relying on that is a decision you should make explicitly by adding the tie-break.