Comparator & Comparable
Custom sort logic in Java — intuition-first. How to write any comparator from first principles.
The ONE Rule
compare(a, b) answers: should a come before b?
💡
negative → a before b | zero → same | positive → b before a
Process — English first, code second
- Say what "a before b" means in plain English
- Express that as math
- Return negative when true
Common Patterns
Ascending
Java
Collections.sort(list, (a, b) -> Integer.compare(a, b));⚠
Never use
a - b directly — integer overflow. Always Integer.compare(a, b).Descending
Java
Collections.sort(list, (a, b) -> Integer.compare(b, a));Sort by absolute value
Java
// [-10, 6, 2, -6, 1, 10] → [1, 2, 6, -6, -10, 10]
Collections.sort(list, (a, b) -> Integer.compare(Math.abs(a), Math.abs(b)));a=5, b=10 |5|-|10| = -5 < 0 → 5 before 10 ✓ a=-6, b=2 |-6|-|2| = 4 > 0 → 2 before -6 ✓ a=-6, b=6 |-6|-|6| = 0 → same ✓
Multi-key Sorting
Java
Collections.sort(list, (a, b) -> {{
int cmp = a.name.compareTo(b.name);
if (cmp != 0) return cmp;
return Integer.compare(a.age, b.age);
}});Comparable vs Comparator
| Feature | Comparable | Comparator |
|---|---|---|
| Logic lives | Inside class | Outside class |
| Method | compareTo(other) | compare(a, b) |
| Orderings | Only ONE | As many as you want |
| Modify class? | YES | NO |
✓
One natural order → Comparable. Multiple orderings or can't modify class → Comparator.