Video in progress
Sort a list by last name, then by first name, with null last names at the end.
I build a chain with Comparator.comparing(User::lastName, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(User::firstName) and pass it to list.sort(...). Because the sort is stable, the order of equal elements is preserved.
📖 Answer
record User(String firstName, String lastName, int age) {}
users.sort(
Comparator.comparing(User::lastName,
Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparing(User::firstName)
);
Without nullsLast, the first null last name throws a NullPointerException. I've seen this a lot on prod.
Other useful parts:
.reversed()reverses the whole chain. To reverse only one field, usethenComparing(User::age, Comparator.reverseOrder());- for a primitive field use
comparingInt(User::age), which does no boxing; - the old way
(a, b) -> a.age() - b.age()is dangerous: the subtraction overflows on large numbers. WriteInteger.compare(a, b).
On small lists the difference isn't noticeable, but if the same comparator is needed in many places, pull it out into a static final field.
Sign up to mark studied questions and save your progress.