Custom Comparators for Complex Objects
What You'll Learn
You'll learn how to create sophisticated comparators using Comparator.comparing() and thenComparing() to find minimum and maximum values in streams based on specific object properties.
The Core Idea
When working with complex objects (like Person or Product), you often need to find the min or max based on specific fields. Instead of writing verbose custom comparators from scratch, Java provides fluent builder methods that let you chain comparison logic elegantly.
Comparator.comparing() extracts a property from your object and creates a comparator based on it. thenComparing() adds secondary (and tertiary, etc.) comparison criteria when the first comparison results in a tie.
Think of it like sorting athletes: first by their score (primary), then by time taken if scores are equal (secondary), then by age if times match (tertiary).
Building Custom Comparators
Here's how you construct multi-level comparators:
// Find person with highest salary, breaking ties by age
Optional<Person> highestPaid = people.stream()
.max(Comparator.comparing(Person::getSalary)
.thenComparing(Person::getAge));
// Find youngest employee, breaking ties alphabetically by name
Optional<Employee> youngest = employees.stream()
.min(Comparator.comparing(Employee::getAge)
.thenComparing(Employee::getName));
// Complex three-level comparison
Optional<Product> featured = products.stream()
.max(Comparator.comparing(Product::getRating)
.thenComparing(Product::getSalesCount)
.thenComparing(Product::getPrice));
The beauty here is readability: your code reads like English. comparing() handles the extraction logic, and you can chain as many thenComparing() calls as needed.
Key Takeaway:
Use Comparator.comparing() to extract object properties for comparison, and chain thenComparing() to add tie-breaking logic, making min/max operations on complex objects both readable and powerful.