Comparable and Comparator Interfaces

In Java, the Comparable and Comparator interfaces are fundamental for sorting objects and customizing sorting orders. They are part of the Java Collections Framework and provide ways to compare objects based on their natural ordering (Comparable) or a defined custom ordering (Comparator). 

Comparable Interface – Natural Ordering

The Comparable interface is used to define a natural order for a class. A class that implements Comparable must override the compareTo() method. This method is called automatically by sorting methods like Collections.sort() or Arrays.sort().

Where is it defined?

package java.lang;
public interface Comparable<T> {
    public int compareTo(T o);
}Code language: PHP (php)

How does it work?

  • The object on which compareTo() is called is compared with the passed object.
  • It returns:
  • A negative integer if the current object is less than the specified object.
    • Zero if they are equal.

    • A positive integer if the current object is greater than the specified object.

This logic is used when we want a default sorting mechanism for our objects.

Example Use Case

If you have a class Student and you want to sort students by their rollNo, you can implement Comparable and define the logic in compareTo().

Comparator Interface – Custom Ordering

Sometimes, a class may need to be sorted in more than one way, or you may want to keep sorting logic outside the class. In these cases, the Comparator interface is more suitable.

Where is it defined?

package java.util;
public interface Comparator<T> {
    int compare(T o1, T o2);
}Code language: PHP (php)

How does it work?

  • You implement this interface in a separate class or as an anonymous class/lambda.
  • It compares two objects externally, without changing the original class.
  • Useful when:
    • The class doesn’t implement Comparable.

    • Multiple sorting logics are required (e.g., by name, by marks, by ID).

Comparable interface Methods

Comparator Interface Methods

Program

import java.util.*;

// Class that implements Comparable (natural order by rollNo)
class Student implements Comparable<Student> {
    int rollNo;
    String name;

    Student(int rollNo, String name) {
        this.rollNo = rollNo;
        this.name = name;
    }

    // Natural order: by rollNo
    public int compareTo(Student other) {
        return this.rollNo - other.rollNo;
    }

    public String toString() {
        return rollNo + " - " + name;
    }
}

// External class that implements Comparator for sorting by name
class NameSorter implements Comparator<Student> {
    public int compare(Student s1, Student s2) {
        return s1.name.compareTo(s2.name);
    }
}

public class SortingExample {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student(3, "Mahesh"));
        students.add(new Student(1, "LotusJavaPrince"));
        students.add(new Student(2, "Paani"));

        System.out.println("Sorting using Comparable (by rollNo):");
        Collections.sort(students);  // Uses compareTo()
        for (Student s : students) {
            System.out.println(s);
        }

        System.out.println("\nSorting using Comparator (by name):");
        Collections.sort(students, new NameSorter());  // Uses Comparator
        for (Student s : students) {
            System.out.println(s);
        }
    }
}
/*
Sorting using Comparable (by rollNo):
1 - LotusJavaPrince
2 - Paani
3 - Mahesh

Sorting using Comparator (by name):
2 - Paani
1 - LotusJavaPrince
3 - Mahesh
*/

Example Usage in Java 8+:

Comparator<Student> byName = Comparator.comparing(Student::getName);
Comparator<Student> byNameDesc = Comparator.comparing(Student::getName).reversed();
Comparator<Student> byNameThenRoll = Comparator.comparing(Student::getName).thenComparing(Student::getRollNo);
Code language: PHP (php)

The Comparator<T> interface is a powerful and flexible tool in Java for defining custom sorting logic outside the class being sorted. Unlike Comparable, which modifies the class itself, Comparator allows external comparison logic and supports multiple sorting strategies.

With Java 8’s enhancements like comparing(), thenComparing(), reversed(), nullsFirst() and nullsLast(), Comparator becomes highly expressive and concise—especially when used with lambda expressions and method references.

Scroll to Top