Video in progress

How do you sort a list by several fields?

I pass the first field to Comparator.comparing(...), add the next with thenComparing(...), and call list.sort(...). For reverse order there is reversed() or Comparator.reverseOrder().

📖 Answer

Say you need to output employees by department first, and within a department by salary in descending order:

record Employee(String dept, String name, long salary) {}

employees.sort(
    Comparator.comparing(Employee::dept)
              .thenComparing(Employee::salary, Comparator.reverseOrder())
              .thenComparing(Employee::name)
);

For primitive fields, comparingInt and comparingLong avoid boxing.

For fields that may be null:

Comparator.comparing(Employee::dept, Comparator.nullsLast(Comparator.naturalOrder()));

Collections.sort(list, cmp) and list.sort(cmp) work the same. Both are stable, so the relative order of equal elements doesn't change. That is why sorting repeatedly, starting from the last key, can sometimes give the right result too, but a chained comparator is easier to read.