Order of Operations: reversed() vs Null Methods
What you'll learn: How the order in which you chain reversed(), nullsFirst(), and nullsLast() dramatically changes how nulls are positioned and elements are sorted.
Understanding Method Chaining Order
When you chain reversed() with nullsFirst() or nullsLast(), the order matters immensely. Each method wraps the previous comparator, so reading the chain from left to right shows you how comparisons flow.
Think of it like wrapping gifts: the innermost box gets wrapped first, then that package gets wrapped again. The outermost wrapper is what people see first.
The Two Patterns
Pattern 1: Null handling then reverse
Comparator.nullsFirst(Comparator.naturalOrder()).reversed()
This says: "First, put nulls first (using natural order for non-nulls), then reverse everything." Result: nulls end up last, and the order flips to descending.
Pattern 2: Reverse then null handling
Comparator.nullsFirst(Comparator.naturalOrder().reversed())
This says: "Use reversed natural order for non-nulls, but keep nulls first." Result: nulls stay first, and non-nulls are in descending order.
The Key Distinction
- When
reversed()is outside (at the end of the chain), it reverses everything, including where nulls land. - When
reversed()is insidenullsFirst()ornullsLast(), it only affects non-null elements; null placement stays as specified.
Practical Example
// nulls at the end, descending order
Comparator.nullsLast(Comparator.naturalOrder()).reversed()
// nulls at the end, descending order (different construction)
Comparator.nullsFirst(Comparator.naturalOrder().reversed()).reversed()
// nulls at the end, ascending order
Comparator.nullsLast(Comparator.naturalOrder())
Key Takeaway: The order of reversed() relative to nullsFirst()/nullsLast() determines whether null placement gets reversed too—outside reverses everything, inside preserves null positioning.