Quick revision
The short answer
The comparator is Comparator.comparing(Employee::department).thenComparing(Employee::salary, Comparator.reverseOrder()).thenComparing(Employee::name, Comparator.nullsLast(Comparator.naturalOrder())). Passing reverseOrder() to the salary key reverses only that key, whereas calling reversed() on the chain would reverse every key before it too. BigDecimal's compareTo ignores scale, so 10.0 and 10.00 sort as equal, the sort is stable for equal elements, and we avoid subtraction-based comparators because they overflow and truncate.
What to remember
In this answer, we built a three-key comparator with Comparator.comparing and thenComparing, reversed only the salary key by passing Comparator.reverseOrder() instead of calling reversed() on the chain, put null names last with Comparator.nullsLast, and saw that BigDecimal's compareTo ignores scale so 120000 and 120000.00 tie. We also saw why subtraction-based comparators truncate and overflow, and that the stable sort keeps the input order of elements that are equal on every key.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The comparator is Comparator.comparing(Employee::department).thenComparing(Employee::salary, Comparator.reverseOrder()).thenComparing(Employee::name, Comparator.nullsLast(Comparator.naturalOrder())). Passing reverseOrder() to the salary key reverses only that key, whereas calling reversed() on the chain would reverse every key before it too. BigDecimal's compareTo ignores scale, so 10.0 and 10.00 sort as equal, the sort is stable for equal elements, and we avoid subtraction-based comparators because they overflow and truncate.
Why this question is asked
Multi-key sorting is everyday work in Java services: reports, admin screens, exports. The Comparator API makes it a one-liner, but that one line contains several decisions that are easy to get wrong, and the bugs are silent: a list comes out in the wrong order, or a null name crashes a report at month end. Interviewers ask this to see whether we know the API well and understand what each part does. In this answer, we will recap how a Comparator works, build the chain one key at a time, look at the reversed() trap, handle nulls, see how BigDecimal compares, and explain why subtraction comparators are wrong.
1A Quick Recap of Comparator
A Comparator<T> has one method, compare(a, b), which returns a negative number if a should come before b, zero if they are equal for sorting purposes, and a positive number if a should come after b. Only the sign matters.
Since Java 8, Comparator has static and default methods that build comparators from key extractors instead of hand-written compare methods. Comparator.comparing(keyExtractor) compares by a key that is Comparable, and thenComparing adds a tie-breaker that is used only when all previous keys are equal. Each method returns a new comparator, so we build the full ordering as a chain.
2Building the Chain One Key at a Time
Here is the full solution, followed by a run on sample data.
| Employee | department | salary (desc) | name (nulls last) |
|---|---|---|---|
| Eng 150000 Ama | Eng | first: highest | not needed |
| Eng 120000.00 Ari | Eng | tie at 120000 | Ari |
| Eng 120000 Bao | Eng | tie at 120000 | Bao |
| Eng 120000 null | Eng | tie at 120000 | null, so last |
| Ops 90000 Cy | Ops, after Eng | not needed | not needed |
Each key is used only to break ties in the previous ones. All Eng employees come before Ops. Within Eng, the 150000 salary comes first because salaries are reversed. The three employees on 120000 tie on salary, so the name decides: Ari, then Bao, then the null name last. Notice that 120000.00 and 120000 tied, which we will come back to.
3The reversed() Trap
A natural mistake is to reach for reversed() to get salaries in descending order. But reversed() applies to the whole comparator it is called on, which includes every key before it.
So the rule is: to reverse one key, pass a reversed comparator for that key, Comparator.reverseOrder() as the second argument of thenComparing, or use reversed() only on a comparator that contains nothing but that key, as in thenComparing(Comparator.comparing(Employee::salary).reversed()).
4Handling null Names
Comparator.naturalOrder() calls compareTo on the values, so a null name would throw NullPointerException. Comparator.nullsLast(other) wraps another comparator: it treats null as greater than every non-null value, so nulls sort to the end, and uses the wrapped comparator when both values are non-null. nullsFirst does the opposite.
The wrapper applies only to the key we put it on. If department or salary can also be null, they need the same treatment, for example Comparator.comparing(Employee::department, Comparator.nullsLast(Comparator.naturalOrder())). Otherwise a single employee with no department crashes the whole sort. Note also that nullsLast protects against a null name, not a null Employee in the list; that would need nullsLast around the whole comparator.
5BigDecimal compareTo Ignores Scale
A BigDecimal has an unscaled value and a scale, the number of digits after the decimal point. 120000 and 120000.00 have the same numeric value but different scales. compareTo compares numeric values only, while equals also compares scale.
For sorting, comparing by value is almost always what we want; an employee earning 120000.00 should not rank differently from one earning 120000. That is why Ari's 120000.00 tied with Bao's 120000 and the name broke the tie. The difference matters elsewhere, for example in a HashSet<BigDecimal> or as map keys, where 10.0 and 10.00 are different elements.
6Why Subtraction-Based Comparators Are Wrong
Older code often writes comparators as (a, b) -> a.x() - b.x(). It looks neat and is subtly broken. For the salary version in this question it is broken in two ways.
When the subtraction overflows, the result has the wrong sign, so the comparator says a is smaller when it is larger. That breaks the comparator contract, and TimSort may even throw 'Comparison method violates its general contract'. The fix is to compare the values themselves: BigDecimal::compareTo through Comparator.comparing, or Integer.compare and Long.compare for primitives, or comparingInt and comparingLong.
7Stability: Equal Elements Keep Their Order
List.sort uses TimSort, which is stable: elements that compare as equal on every key keep the order they had in the input. With our comparator, two employees with the same department, the same salary and the same name, or two with null names on the same salary, stay in their original relative order. That makes the result deterministic for a given input, which is useful for reports and for tests that compare output.
If we need a fully deterministic order regardless of input order, we add a final unique key, such as an employee id, as the last thenComparing.
8Follow-up questions
Why is (a, b) -> a.salary().intValue() - b.salary().intValue() wrong?
Because it has two defects. intValue() truncates the fraction, so salaries such as 10.90 and 10.10 compare as equal, and it silently drops high-order bits for values that do not fit in an int. And subtracting two ints can overflow, producing a result with the wrong sign, so the comparator reports the wrong order and can violate the contract that compare(a, b) and compare(b, a) have opposite signs. Use Comparator.comparing(Employee::salary), which calls BigDecimal.compareTo.
Why does Comparator.comparing(e -> e.salary()).reversed() sometimes fail to compile?
With a lambda, the compiler cannot infer the type of e when the comparing call is followed by .reversed(), because inference does not flow backwards through the method chain, so e is treated as Object. A method reference such as Employee::salary, or an explicit type, (Employee e) -> e.salary(), fixes it.
Should the comparator be a constant?
Yes, if it is used in several places. A static final Comparator<Employee> BY_DEPARTMENT_SALARY_NAME documents the ordering with a name, is built once, and keeps every screen and export consistent. Comparators built this way are immutable and thread-safe.
9Conclusion
In this answer, we built a three-key comparator with Comparator.comparing and thenComparing, reversed only the salary key by passing Comparator.reverseOrder() instead of calling reversed() on the chain, put null names last with Comparator.nullsLast, and saw that BigDecimal's compareTo ignores scale so 120000 and 120000.00 tie. We also saw why subtraction-based comparators truncate and overflow, and that the stable sort keeps the input order of elements that are equal on every key.
Open with
I would write Comparator.comparing(Employee::department), then thenComparing(Employee::salary, Comparator.reverseOrder()), then thenComparing(Employee::name, Comparator.nullsLast(Comparator.naturalOrder())). Each thenComparing is only used to break ties in the keys before it. The important detail is how I reverse salary: I pass reverseOrder as the comparator for that key only.
Then, if they want more
If I called reversed() on the chain after salary, it would reverse the department order too, so Ops would come before Eng. For the name, nullsLast wraps natural order so null names sort to the end instead of throwing NullPointerException; if department or salary could be null, they'd need the same wrapper.
For salary I rely on BigDecimal's compareTo, which compares numeric value and ignores scale, so 120000 and 120000.00 tie and the name decides. That's what we want for sorting, though equals would say they're different.
I'd avoid a subtraction comparator like intValue minus intValue: intValue truncates fractions and drops high bits, and subtracting ints can overflow and give the wrong sign, which breaks the comparator contract. Finally, List.sort uses TimSort, which is stable, so employees equal on all three keys keep their input order.
If I need a fully deterministic order, I add a unique id as a last key, and I'd keep the comparator as a named constant.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a Comparator<Employee> that sorts by department ascending, then salary descending...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/7e568f7659/