Represent an object as ordered comparison keys and compare them lexicographically: compare the first key, then consult later keys only when earlier keys are equal. This keeps compareTo implementations aligned with the comparison contract. section 7.13
Special cases must become keys
A comparator that returns -1 whenever this connection is secure mishandles two secure connections. Model security as the first key and url as the second, using Boolean.compare or ComparisonChain; otherwise swapping equal-category objects can violate the contract. section 7.13
Comparator<Person> PERSON_COMPARATOR =
Comparator.comparing((Person p) -> p.name)
.thenComparing(p -> p.age);
Use Comparator.comparing(...).thenComparing(...) to express the key sequence directly; Guava ComparisonChain provides a similar fluent alternative. section 7.13
Avoid these comparison mistakes:
- Handle nullable keys explicitly instead of returning zero merely because one or both values are null. section 7.13
- Do not return zero when primary keys differ; compare the primary key before the secondary key. section 7.13
