Multiple Comparators for Different Sort Orders
What You'll Learn
You'll learn how to create several Comparator instances for the same class, allowing you to sort the same data in different ways depending on your needs.
The Core Idea
Think of a music library: sometimes you want to browse songs by title, other times by artist, and sometimes by release date. The songs themselves don't change, but your sorting strategy does.
In Java, you can define multiple Comparator objects for a single class—each one representing a different "lens" through which to order your objects. One comparator might sort Person objects by name alphabetically, another by age numerically, and yet another by registration date chronologically.
How It Works
Instead of a class having just one natural ordering (via Comparable), you create separate Comparator instances—often as static fields or methods in your class:
public class Employee {
private String name;
private int age;
private LocalDate hireDate;
// constructors, getters...
// Comparator by name
public static final Comparator<Employee> BY_NAME =
(e1, e2) -> e1.name.compareTo(e2.name);
// Comparator by age
public static final Comparator<Employee> BY_AGE =
(e1, e2) -> Integer.compare(e1.age, e2.age);
// Comparator by hire date
public static final Comparator<Employee> BY_HIRE_DATE =
(e1, e2) -> e1.hireDate.compareTo(e2.hireDate);
}
Now you can sort the same list in different ways:
Collections.sort(employees, Employee.BY_NAME);
// or
Collections.sort(employees, Employee.BY_AGE);
// or
Collections.sort(employees, Employee.BY_HIRE_DATE);
Each sort call uses a different ordering strategy without modifying the Employee class's natural order or requiring multiple classes.
Key Takeaway: Multiple Comparator instances let you define flexible, reusable sorting strategies for the same class, choosing the right order based on context rather than being locked into a single natural ordering.