Comparator Interface in Java
Sorting objects in Java is an essential skill, especially when dealing with collections of custom objects. In the previous blog, we learned about the Comparable
interface, which defines the natural ordering of objects. But what if we want multiple sorting criteria (e.g., sorting by name, then by age)? This is where the Comparator interface comes in!
Let’s explore what the Comparator
interface is, why we need it, and how to implement it with examples.
1. What is the Comparator Interface?#
The Comparator
interface in Java allows us to define custom sorting logic for objects. Unlike Comparable
, which enforces a natural ordering, Comparator
gives us the flexibility to define multiple ways to compare objects.
Syntax:#
- If o1 should come before o2, return a negative number.
- If o1 is equal to o2, return zero.
- If o1 should come after o2, return a positive number.
2. Why Use Comparator?#
Problem Without Comparator:#
Let’s say we have a Student
class and we want to sort students by name and age. If we use Comparable
, we can only define one sorting rule. But with Comparator
, we can have multiple sorting criteria.
3. Sorting Using Comparator#
Example 1: Sorting Students by Age#
Output:#
4. Sorting by Name (Alphabetically)#
Now, we can sort students by name:
Output:#
5. Sorting in Descending Order#
To sort by age in descending order, simply reverse the subtraction:
Output:#
6. Using Lambda Expressions for Comparator (Java 8+)#
Java 8 introduced lambda expressions, making sorting even easier:
For descending order:
Or even:
For sorting by name:
7. Sorting by Multiple Criteria#
What if we want to sort by name first, and then age?
Explanation:#
- Sorts by name first.
- If names are the same, sorts by age.
8. Key Takeaways#
Comparator
is used for custom sorting.- We can define multiple
Comparator
classes for different sorting criteria. - Lambda expressions make sorting easier (Java 8+).
- We can chain comparators for multi-level sorting.
Conclusion#
The Comparator
interface is a powerful tool when you need flexible sorting options. While Comparable
defines the default sorting order, Comparator
gives us multiple ways to compare objects.