Comparator.comparing is a Java factory method that builds a comparator by extracting a comparison key from each object. Use it when an ordering should follow the values of one or more fields. section 7.13
The common mistake is returning 0 merely because the first key differs. That treats distinct objects as equivalent and can violate the comparator contract. Compare the first key, then continue with later keys only when it ties. section 7.13
Compare a sequence of keys
For MyObject records with x and y fields, use Comparator.comparing(MyObject::x).thenComparing(MyObject::y). This orders by x and uses y as the tie-breaker. If x is intentionally irrelevant, Comparator.comparing(MyObject::y) provides a complete alternative order. section 7.13
Avoid fragile comparison implementations by following these rules:
- Represent the object as an ordered sequence of keys. section 7.13
- Use thenComparing for tie-breakers and predefined primitive comparison methods where appropriate. section 7.15
- Test comparator contract properties with randomized objects; sorting datasets larger than 31 elements can expose violations through TimSort. section 7.13
- Handle nullable keys with nullsFirst or nullsLast rather than silently treating unrelated objects as equal. section 7.15
