Lesson Completion
Back to course

Comparable and Comparator: Sorting Made Smart

Intermediate
15 minutes4.9Java

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: Comparable defines natural ordering (how objects compare by default). Comparator defines custom ordering (alternative sorting strategies). Both are interfaces that enable sorting collections. Comparable is "built-in" sorting; Comparator is pluggable sorting.

Think of Amazon product listings. Default sort (Comparable) might be by "Relevance." But you can choose (Comparator) to sort by "Price," "Rating," or "Newest."


2. Conceptual Clarity (The "Simple" Tier)

💡 The Analogy: Sorting Books

  • Comparable: Books naturally sort by title (A-Z) -Comparator: You can also sort by author, year, or rating

Same books, different sorting strategies!


3. Technical Mastery (The "Deep Dive")

Comparable Interface

java
public interface Comparable<T> { int compareTo(T o); }
  • Returns negative if this < o
  • Returns zero if this == o
  • Returns positive if this > o

Comparator Interface

java
public interface Comparator<T> { int compare(T o1, T o2); }

4. Interactive & Applied Code

java
class Employee implements Comparable<Employee> { String name; int salary; Employee(String name, int salary) { this.name = name; this.salary = salary; } // Natural ordering: by name @Override public int compareTo(Employee other) { return this.name.compareTo(other.name); } @Override public String toString() { return name + "($" + salary + ")"; } } public class Main { public static void main(String[] args) { List<Employee> employees = Arrays.asList( new Employee("Alice", 70000), new Employee("Bob", 60000), new Employee("Charlie", 80000) ); // Sort by natural ordering (name) Collections.sort(employees); System.out.println("By name: " + employees); // Custom Comparator: by salary Comparator<Employee> bySalary = (e1, e2) -> Integer.compare(e1.salary, e2.salary); Collections.sort(employees, bySalary); System.out.println("By salary: " + employees); // Java 8+ Comparator methods employees.sort(Comparator.comparingInt(e -> e.salary).reversed()); System.out.println("By salary (desc): " + employees); } }

5. The Comparison & Decision Layer

FeatureComparableComparator
Packagejava.langjava.util
MethodcompareTo(T o)compare(T o1, T o2)
Use CaseNatural/default orderingCustom/multiple orderings
Modify Class?Yes (implement interface)No (external)

6. The "Interview Corner" (The Edge)

The "Killer" Interview Question: "When do you use Comparable vs. Comparator?" Answer:

  • Comparable: When there's ONE logical natural ordering (e.g., Employee by ID)
  • Comparator: When you need MULTIPLE sorting options (by name, salary, dept)

Pro-Tip: Java 8+ Comparator chaining:

java
employees.sort( Comparator.comparing(Employee::getDept) .thenComparing(Employee::getSalary) .reversed() );

Topics Covered

Object-Oriented ProgrammingAbstraction

Tags

#java#abstraction#interfaces#abstract-classes#contract-programming

Last Updated

2025-02-01