Course contentsShow
← Java
Lesson 1343 of 2,87030. Comparable and ComparatorFree lesson

thenComparing() with Method References

Combine comparing() and thenComparing() with method references for multi-level sorting without verbosity.

thenComparing() with Method References

What you'll learn: How to elegantly chain multiple sorting criteria using method references with thenComparing() for clean, readable multi-level sorts.


The Core Idea

You've already seen how to create multi-level sorts by chaining thenComparing() with lambda expressions. When your secondary (or tertiary) sorting criteria map directly to getter methods, you can use method references instead, making your code even more concise and expressive.

Just as Comparator.comparing() accepts method references, so does thenComparing(). This lets you build complex sorting logic in a single fluent chain without any verbose lambda syntax.

How It Works

Instead of writing:

Comparator<Person> byLastThenFirst = 
    Comparator.comparing(p -> p.getLastName())
              .thenComparing(p -> p.getFirstName());

You can write:

Comparator<Person> byLastThenFirst = 
    Comparator.comparing(Person::getLastName)
              .thenComparing(Person::getFirstName);

Both do the same thing—sort by last name, then by first name—but the method reference version is cleaner and more readable.

Multi-Level Example

You can chain as many levels as needed:

Comparator<Employee> multiSort = 
    Comparator.comparing(Employee::getDepartment)
              .thenComparing(Employee::getSalary)
              .thenComparing(Employee::getLastName);

This sorts employees first by department, then by salary within each department, then by last name if salary is equal—all in one elegant expression.

Why This Matters

Method references shine in sorting chains because they eliminate visual noise. The intent becomes crystal clear: "sort by this field, then that field, then that other field." No parameter names, no arrow syntax—just pure declarative logic.

Key Takeaway:
Use thenComparing() with method references to build multi-level sorts that are compact, type-safe, and immediately understandable—combining the power of chaining with the clarity of direct method invocation.