Card 08/ 09
All 9 cards
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.
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 — or Cal, Ada, Bea | The whole comparator; the two 36s still tie |
| 3 | Cal, Ada, Bea | The whole chain, including the name tie-break |
| 4 | Ada, Cal, Bea | The 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.