Comparator Composition & Consistency β Interview Questions
Reviewed by Gurusankar M.
β‘ Short Answer
Build multi-key ordering with Comparator.comparing(...).thenComparing(...), use comparingInt/Long/Double to avoid boxing, and handle nulls with nullsFirst/nullsLast. The subtle rule: for sorted sets and maps (TreeSet/TreeMap), ordering should be consistent with equals β two elements the comparator calls 'equal' (compare == 0) are treated as the same key, even if equals() disagrees, which can silently drop elements.
βCoffee Chat Question
Concept Made Simple
βHow do you compose Comparators safely, and why must ordering be consistent with equals?β
π§ Mind Map Answer
Remember It Faster
For TreeSet/TreeMap, the *comparator* β not equals() β defines identity. If compare() returns 0 for two 'different' objects, the set keeps only one. That's the 'my TreeSet lost elements' bug.
Comparators must obey the contract: consistent, transitive, and antisymmetric. A comparator like (a,b) -> a.x - b.x can overflow for large ints β use Integer.compare / comparingInt instead.
Key takeaway: compose comparators declaratively, keep them null-safe and overflow-safe, and make sure sorted-collection ordering agrees with equals.
β¨οΈHands-on Keyboard
Learn by Doing
Comparator<Employee> byDeptThenSalaryDesc =
Comparator.comparing(Employee::dept)
.thenComparing(Comparator.comparingInt(Employee::salary).reversed())
.thenComparing(Employee::name, Comparator.nullsLast(naturalOrder()));
employees.sort(byDeptThenSalaryDesc);π₯What If?
Think Beyond the Expected
You add 100 distinct objects to a TreeSet but size() is 60 β what happened?
The comparator returned 0 for elements you consider different, so TreeSet treated them as duplicates and dropped them. TreeSet/TreeMap use compareTo/compare (not equals/hashCode) to decide membership, so ordering that isn't consistent with equals silently collapses distinct elements. Fix it by making the comparator a total order that ends in a tie-breaker unique per element (e.g. an id), so compare() only returns 0 for genuinely equal objects.
πReal World
Multi-column sorting in APIs (sort by status, then date, then id), leaderboards, and priority ordering all use composed comparators; the 'consistent with equals' rule bites teams who put domain objects in a TreeSet keyed by a non-unique field and quietly lose rows. Adding a unique tie-breaker is the standard fix.
π―Interviewer's Expectation
Keywords they're listening for:
β οΈCommon Mistakes
- βUsing a - b (overflow) instead of Integer.compare
- βPutting objects in a TreeSet with a non-unique comparator
- βIgnoring nulls and getting NullPointerException while sorting
β Best Practices
- βCompose with comparing/thenComparing for readability
- βEnd sorted-collection comparators with a unique tie-breaker
- βUse comparingInt/Long/Double to avoid boxing
πFollow-up Questions
- 1Why prefer Integer.compare over a - b in a comparator?
- 2When is natural ordering (Comparable) better than a Comparator?
- 3How does this interact with equals()/hashCode()?
π§©Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly β AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Ordering (Advanced Java) Interview question: "How do you compose Comparators safely, and why must ordering be consistent with equals?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
β Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission β at no extra cost to you. It helps keep Full Stack Interview Guru free.