Video in progress

How do you sort elements in a stream by several fields and in reverse order?

You give sorted() a Comparator: Comparator.comparing(...) for the main field, thenComparing(...) for the second field, and reversed() or Comparator.reverseOrder() for reverse order.

📖 Answer

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

List<Employee> sorted = employees.stream()
        .sorted(Comparator.comparing(Employee::dept)
                .thenComparing(Employee::salary, Comparator.reverseOrder())
                .thenComparing(Employee::name))
        .toList();

Here: first by department in alphabetical order, within one department the higher salaries come first, and if the salary is equal, by name.

There's one trap. .reversed() reverses the entire comparator that comes before it:

Comparator.comparing(Employee::dept).thenComparing(Employee::salary).reversed();
// the department order got reversed too!

To reverse just one field, write thenComparing(key, Comparator.reverseOrder()) as above.

For numeric fields there are comparingInt / comparingLong, which work without boxing. If the elements are Comparable themselves, plain sorted() with no arguments is enough.