library
intermediateComparable, Comparator & Fluent Sorting
Define natural ordering with Comparable, build custom orderings with Comparator's fluent API, and use null-safe comparisons.
Java provides two interfaces for sorting:
Comparable = a student's GPA (built-in ranking). Comparator = different ranking criteria (by name, by age, by grade) that a registrar can apply without changing the student record.
Key Concepts
1
Comparable<T>: defines a class's natural ordering. The class itself implements compareTo(). One ordering per class. Used by: Collections.sort(list), TreeSet, TreeMap.
2
Comparator<T>: defines an external ordering. Separate object, can have multiple orderings for the same class. Used by: Collections.sort(list, comparator), TreeSet(comparator), Stream.sorted(comparator).
3
Comparator fluent API (Java 8):
- Comparator.comparing(keyExtractor): primary sort
- .thenComparing(keyExtractor): secondary sort
- .reversed(): reverse the order
- Comparator.naturalOrder(), Comparator.reverseOrder()
- Comparator.nullsFirst(), Comparator.nullsLast()
4
Contract: compareTo/compare must be consistent with equals for correct behavior in TreeSet/TreeMap. If a.compareTo(b) == 0, then a.equals(b) should be true.
5
Return values:
- Negative: this < other (or first < second for Comparator)
- Zero: equal
- Positive: this > other
6
Don't use subtraction for compareTo (a - b) with integers — it can overflow. Use Integer.compare(a, b) instead.