Sorting with Comparator.comparing() and Method References
Fast recall
Quick revision
Core answer
Practical Java 8 API knowledge—can you use method references with real library methods like Comparator in everyday sorting scenarios.
Writing manual lambda comparators like (a, b) -> a.getName().compareTo(b.getName()) when Comparator.comparing with a method reference is built for exactly this case.
Show multi-field sorting with thenComparing and mention reversed for descending order, demonstrating fluent API knowledge beyond basic usage.
Interview-ready guide
Interview answer
Comparator.comparing takes a key extractor. For Comparator.comparing(Person::getName), each Person becomes the receiver of getName, and the returned names are compared in their natural order. Add thenComparing when equal primary keys need a tie-breaker. Call reversed() on the comparator whose order you want to flip; reversing the finished chain flips every criterion. For an int key, comparingInt(Employee::salary) avoids boxing. Null handling is explicit: nullsLast around the finished comparator handles null elements, while a null-aware key comparator passed to comparing handles a null name or other extracted value.
Sorting with Comparator.comparing() and Method References
Direct Answer
Use Comparator.comparing() with a method reference to extract the field you want to sort by. For example, list.sort(Comparator.comparing(Person::getName)) sorts by name. You can chain thenComparing() for multi-field sorting and call reversed() for descending order. It's cleaner than writing manual compare logic.
Code Example
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
record Employee(String name, String department, int salary) {}
public class ComparatorDemo {
public static void main(String[] args) {
var employees = List.of(
new Employee("Alice", "Engineering", 85_000),
new Employee("Bob", "Engineering", 90_000),
new Employee("Charlie", "Sales", 75_000)
);
var bySalaryDescending = employees.stream()
.sorted(Comparator.comparingInt(Employee::salary).reversed())
.toList();
var byDepartmentThenSalary = employees.stream()
.sorted(Comparator.comparing(Employee::department)
.thenComparing(Comparator.comparingInt(Employee::salary).reversed()))
.toList();
// Arrays.asList permits a null element; List.of does not.
var names = Arrays.asList("Alice", null, "Bob");
names.sort(Comparator.nullsLast(Comparator.naturalOrder()));
// This handles a null key returned by Employee::name.
Comparator<Employee> byNullableName = Comparator.comparing(
Employee::name, Comparator.nullsLast(Comparator.naturalOrder()));
}
}
Common Mistakes & Pitfalls
- Assuming null safety is automatic:
Comparator.comparing(Person::getName)can fail ifgetName()returns null. UseComparator.comparing(Person::getName, Comparator.nullsLast(Comparator.naturalOrder()))when null keys are allowed. - Handling the wrong kind of null:
Comparator.nullsLast(comparator)handles null elements; the null-aware comparator passed tocomparinghandles null extracted keys. - Reversing too much: calling
reversed()after a complete multi-field comparator reverses every criterion. Reverse only the component comparator when just one field should be descending.
Check your understanding
Answer these without looking back at the article.
- How do you sort in descending order using Comparator?
- How do you sort by multiple fields?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.