Back to Study Material Java

Comparable and Comparator in Java

Java provides two interfaces for defining the ordering of objects: Comparable and Comparator. Understanding when and how to use each is a fundamental skill...

Comparable and Comparator in Java

Sorting Objects: Two Approaches

Java provides two interfaces for defining the ordering of objects: Comparable and Comparator. Understanding when and how to use each is a fundamental skill for working with sorted collections and sorting algorithms.

Comparable is in the java.lang package and is implemented by a class to define its natural ordering. It requires implementing a single method: compareTo(T other), which returns a negative integer if this object is less than other, zero if equal, and a positive integer if greater. Classes like String, Integer, and LocalDate implement Comparable so they sort naturally when placed in a TreeSet or sorted with Collections.sort().

class Student implements Comparable<Student> { String name; int grade; Student(String name, int grade) { this.name = name; this.grade = grade; } @Override public int compareTo(Student other) { return Integer.compare(this.grade, other.grade); } }

Comparator, in java.util, is an external comparison strategy. It lets you sort objects in a way that is different from their natural order, or sort objects that do not implement Comparable. Comparator has a single abstract method compare(T o1, T o2).

List<Student> students = new ArrayList<>(); students.sort(Comparator.comparing(s -> s.name));

Java 8 enriched Comparator with default methods like thenComparing(), reversed(), and static helpers like comparing() and comparingInt(), enabling fluent chaining of multiple sort criteria.

The key difference is that Comparable defines one fixed natural ordering inside the class, while Comparator defines a flexible external ordering that can vary. A class can implement Comparable once but can have many different Comparators.

Interview tip: A common interview question asks when to use Comparable versus Comparator. The clean answer is: use Comparable when the ordering is intrinsic to the class (like sorting employees by ID), and use Comparator when you need multiple orderings or cannot modify the class.