Comparator.comparing() with Method References
What you'll learn: How to create clean, readable comparators using Comparator.comparing() combined with method references to sort objects by a single property.
The Core Idea
Instead of manually implementing the compare method or writing verbose lambda expressions, Java 8 introduced Comparator.comparing() — a factory method that generates a comparator for you. When you combine it with method references, you get remarkably concise sorting logic.
Think of it like this: you point at which property matters ("sort by name" or "sort by age"), and Java builds the entire comparison machinery for you.
How It Works
The Comparator.comparing() method takes a function that extracts the property you want to compare. When you use a method reference, you're simply telling it which getter to use:
Comparator<Person> byName = Comparator.comparing(Person::getName);
This creates a comparator that extracts each person's name and compares them using the natural ordering of strings. No manual compare implementation needed!
Example Usage
List<Person> people = Arrays.asList(
new Person("Charlie", 35),
new Person("Alice", 28),
new Person("Bob", 42)
);
// Sort by name using method reference
Collections.sort(people, Comparator.comparing(Person::getName));
// Result: Alice, Bob, Charlie
// Sort by age
Collections.sort(people, Comparator.comparing(Person::getAge));
// Result: Alice (28), Charlie (35), Bob (42)
The method reference Person::getName is shorthand for the lambda person -> person.getName(). Both work, but method references are cleaner when you're simply calling a getter.
Key Takeaway: Comparator.comparing() with method references provides a declarative, one-line way to create comparators by specifying which property to sort by, eliminating boilerplate code and improving readability.