</>

Technology

Core Java

Difficulty

Intermediate

Interview Question

What is the difference between Comparable and Comparator in Java?

Answer

Comparable vs Comparator in Java

Both are used for sorting objects, but they differ in where and how they define sorting logic.

Comparable — Natural Ordering (built into the class)

Implements java.lang.Comparable<T>. The class itself defines how its objects are ordered.

Java
public class Employee implements Comparable<Employee> {
    private String name;
    private double salary;

    public Employee(String name, double salary) {
        this.name   = name;
        this.salary = salary;
    }

    // Natural order = sort by salary ascending
    @Override
    public int compareTo(Employee other) {
        return Double.compare(this.salary, other.salary);
    }

    // Getters...
}

List<Employee> employees = new ArrayList<>();
employees.add(new Employee("Bob", 75000));
employees.add(new Employee("Alice", 95000));
employees.add(new Employee("Charlie", 60000));

Collections.sort(employees);  // uses compareTo automatically
// Result: Charlie(60k), Bob(75k), Alice(95k) — sorted by salary ascending

Comparator — External Custom Ordering

Implements java.util.Comparator<T>. Defined outside the class — multiple comparators possible.

Java
// Sort by name
Comparator<Employee> byName = Comparator.comparing(Employee::getName);

// Sort by salary descending
Comparator<Employee> bySalaryDesc = Comparator
    .comparingDouble(Employee::getSalary)
    .reversed();

// Sort by salary, then by name (chained)
Comparator<Employee> bySalaryThenName = Comparator
    .comparingDouble(Employee::getSalary)
    .thenComparing(Employee::getName);

// Use with sort
employees.sort(byName);
employees.sort(bySalaryDesc);
employees.sort(bySalaryThenName);

// Inline lambda comparator
employees.sort((e1, e2) -> e1.getName().compareTo(e2.getName()));

compareTo / compare Return Values

ReturnMeaning
Negative (< 0)this / first object comes BEFORE
Zero (0)Objects are equal
Positive (> 0)this / first object comes AFTER

Comparison Table

FeatureComparableComparator
Packagejava.langjava.util
MethodcompareTo(T)compare(T, T)
Modifies class✅ Yes (implement in class)❌ No (external)
Multiple orderings❌ One only✅ Multiple
Lambda-friendlyNo✅ Yes
Collections.sort()✅ No comparator needed✅ Pass comparator

When to Use

  • Comparable: One natural ordering that makes sense for the class (e.g., String sorts alphabetically, Integer numerically)
  • Comparator: Multiple sort criteria, sorting third-party classes, complex comparisons

In Automation Testing

Java
// Sort test data alphabetically by username
List<TestUser> users = getTestUsers();
users.sort(Comparator.comparing(TestUser::getUsername));

// Verify dropdown is sorted
List<String> options = getDropdownOptions();
List<String> expected = new ArrayList<>(options);
Collections.sort(expected); // natural alphabetical order
assertEquals(expected, options, "Dropdown is not sorted alphabetically");

// Sort test results by execution time
testResults.sort(Comparator.comparingLong(TestResult::getDurationMs));

Follow AutomateQA

Related Topics