ArraysSorting

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

  1. Say what "a before b" means in plain English
  2. Express that as math
  3. 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

FeatureComparableComparator
Logic livesInside classOutside class
MethodcompareTo(other)compare(a, b)
OrderingsOnly ONEAs many as you want
Modify class?YESNO
One natural order → Comparable. Multiple orderings or can't modify class → Comparator.