Comparator as Strategy Pattern in Java
Fast recall
Quick revision
Core answer
Comparator is a Strategy for ordering two T values. Sorting APIs accept that behavior as an argument, so the same data can be ordered by name, price, or date without changing its class. The comparator does not choose or represent the sorting algorithm itself; different Java APIs and data types may use different sort implementations.Interview-ready guide
Interview answer
Comparator demonstrates Strategy because it packages one ordering rule behind a common interface. A sorting operation receives the comparator and calls compare without knowing whether the rule uses price, name, or date. I can pass a different comparator for the same list, compose rules with thenComparing, or use a lambda, while the sorting API remains unchanged. The comparator is not the sorting algorithm itself; Java may use different sort implementations for different APIs and data types. It only defines the relative order and must obey the comparator contract.
Comparator as Strategy Pattern in Java
Direct Answer
Comparator<T> is a Strategy for ordering two T values. Sorting APIs accept that behavior as an argument, so the same data can be ordered by name, price, or date without changing its class. The comparator does not choose or represent the sorting algorithm itself; different Java APIs and data types may use different sort implementations.
Common Mistakes & Pitfalls
- Calling Comparator the sorting algorithm: it supplies pairwise ordering; the sorting API chooses its implementation.
- Breaking the contract: inconsistent, non-transitive comparisons can produce wrong results or runtime failures.
- Subtracting numeric fields:
a - bmay overflow; useInteger.compare,Long.compare, or comparator helpers. - Forgetting null policy: use
nullsFirstornullsLastwhen null is allowed. - Ignoring composition:
thenComparingandreversedare clearer than duplicated branching.
Check your understanding
Answer these without looking back at the article.
- How does Comparator.reversed() work as strategy composition?
- What is the difference between Comparable and Comparator?
- How would you sort by one field and break ties with another?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.