Comparator.comparing() with Lambda Expressions
You'll learn how to use lambda expressions inside Comparator.comparing() to create flexible, inline sorting logic without separate method references.
The Core Idea
While method references (Person::getName) are concise when you have a ready-made getter, lambda expressions give you the power to define custom key extraction logic right on the spot. Instead of referencing an existing method, you write a short function that transforms each object into the value you want to sort by.
This becomes invaluable when you need to sort by calculated values, combine fields, or apply transformations before comparing.
Basic Syntax
Comparator.comparing(person -> person.getLastName().toLowerCase())
The lambda person -> person.getLastName().toLowerCase() is a key extractor function. It takes a Person object and returns the lowercase version of the last name—your sort key.
When Lambda Expressions Shine
Use lambdas with comparing() when you need to:
- Transform before comparing: Sort strings case-insensitively, trim whitespace, or apply calculations
- Access nested properties:
order -> order.getCustomer().getAddress().getZipCode() - Perform inline logic:
employee -> employee.getSalary() * 1.15(compare projected raises) - Chain operations:
product -> product.getName().substring(0, 3)(sort by first three characters)
List<Student> students = new ArrayList<>();
// Sort by grade percentage (calculated inline)
students.sort(Comparator.comparing(s -> s.getScore() / s.getMaxScore()));
// Sort by length of email address
students.sort(Comparator.comparing(s -> s.getEmail().length()));
Key Takeaway: Lambda expressions with Comparator.comparing() let you define custom, inline key extraction logic for sorting—perfect when you need to transform, calculate, or navigate complex object structures before comparing.