Collections Framework
Comparator Interface
Analyze the Comparator interface custom sorting contracts, functional structures, and chaining utilities.
Interview: Focuses on comparing compare vs compareTo, functional interface lambdas, and chaining comparator methods.
The java.util.Comparator interface is a functional interface used to define custom sorting orders external to the objects being compared. It is useful when sorting objects that do not have a natural ordering, or when sorting by different fields.
External Sort
Separates sorting logic from the class model, allowing multiple sorting criteria for the same class.
Functional Interface
Declares the single abstract method compare(T o1, T o2), allowing it to be implemented using lambda expressions.
Comparator Chain
Supports chaining using helper methods like thenComparing to resolve sorting ties on secondary fields.
Comparable vs Comparator
| Feature | Comparable | Comparator |
|---|---|---|
| Package | java.lang |
java.util |
| Method | compareTo(T o) |
compare(T o1, T o2) |
| Implementation | Implemented directly by the target class. | Implemented in an external class or lambda. |
| Sorting Modes | Supports only one natural sort order. | Supports multiple, custom sorting orders. |
Common Pitfalls
- Null values during comparison: Passing null values to comparator fields, raising a
NullPointerException. Use null-safe comparators likeComparator.nullsFirst. - Inconsistent sorting order: Writing sorting criteria that do not align with
equals(), which can cause unexpected behavior in sorted sets.
Best Practices
- Use static factory builders: Build comparators using static methods:
Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge). - Handle nulls explicitly: Wrap fields in null-safe comparator decorators when null values are expected.
Interview-Relevant Information
Q1: What is the main difference between Comparable and Comparator?
Answer: Comparable defines the default natural ordering of a class and is implemented directly by that class. Comparator defines custom sorting orders external to the class, allowing multiple sorting criteria.
Q2: How do you sort a collection using multiple criteria with a Comparator?
Answer: Chain comparators using the thenComparing method: Comparator.comparing(User::getLastName).thenComparing(User::getFirstName).
Quick Checklist
Can you state the packages for Comparable and Comparator, compare their signature parameters, and write a two-field chained comparator using Java 8 syntax? If yes, you understand Comparator interface.
Use Cases
Allowing users to sort tables dynamically by columns (e.g. price, name, date).
Resolving ties in job schedulers using secondary task priorities.
Common Mistakes
Failing to handle null values inside custom comparison functions.
Creating complex, unreadable lambda chains instead of using static helper methods.