Java Programming Handbook

    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:#

    import java.util.Comparator; public interface Comparator<T> { int compare(T o1, T o2); }
    • 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#

    import java.util.*; class Student { int id; String name; int age; Student(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } @Override public String toString() { return id + " - " + name + " - Age: " + age; } } class AgeComparator implements Comparator<Student> { @Override public int compare(Student s1, Student s2) { return s1.age - s2.age; // Sorting by age in ascending order } } public class Main { public static void main(String[] args) { List<Student> students = new ArrayList<>(); students.add(new Student(3, "Alice", 22)); students.add(new Student(1, "Bob", 20)); students.add(new Student(2, "Charlie", 21)); Collections.sort(students, new AgeComparator()); System.out.println(students); } }

    Output:#

    1 - Bob - Age: 20 2 - Charlie - Age: 21 3 - Alice - Age: 22

    4. Sorting by Name (Alphabetically)#

    class NameComparator implements Comparator<Student> { @Override public int compare(Student s1, Student s2) { return s1.name.compareTo(s2.name); } }

    Now, we can sort students by name:

    Collections.sort(students, new NameComparator());

    Output:#

    3 - Alice - Age: 22 1 - Bob - Age: 20 2 - Charlie - Age: 21

    5. Sorting in Descending Order#

    To sort by age in descending order, simply reverse the subtraction:

    @Override public int compare(Student s1, Student s2) { return s2.age - s1.age; // Sorting by age in descending order }

    Output:#

    3 - Alice - Age: 22 2 - Charlie - Age: 21 1 - Bob - Age: 20

    6. Using Lambda Expressions for Comparator (Java 8+)#

    Java 8 introduced lambda expressions, making sorting even easier:

    Collections.sort(students, (s1, s2) -> s1.age - s2.age);

    For descending order:

    Collections.sort(students, (s1, s2) -> s2.age - s1.age);

    Or even:

    students.sort(Comparator.comparingInt(s -> s.age));

    For sorting by name:

    students.sort(Comparator.comparing(s -> s.name));

    7. Sorting by Multiple Criteria#

    What if we want to sort by name first, and then age?

    students.sort( Comparator.comparing(Student::getName) .thenComparingInt(Student::getAge) );

    Explanation:#

    1. Sorts by name first.
    2. 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.

    Last updated on Apr 09, 2025