Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a Comparator<Employee> that sorts by department ascending, then salary descending, then name ascending with nulls last for name. Employee is a record(String department, BigDecimal salary, String name).

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.

Java
record Employee(String department, BigDecimal salary, String name) {}
Comparator<Employee> order = Comparator
.comparing(Employee::department) // 1. department A-Z
.thenComparing(Employee::salary, Comparator.reverseOrder()) // 2. salary high to low
.thenComparing(Employee::name, Comparator.nullsLast(Comparator.naturalOrder())); // 3. name A-Z, nulls last
List<Employee> staff = new ArrayList<>(List.of(
new Employee("Ops", new BigDecimal("90000"), "Cy"),
new Employee("Eng", new BigDecimal("120000"), null),
new Employee("Eng", new BigDecimal("150000"), "Ama"),
new Employee("Eng", new BigDecimal("120000"), "Bao"),
new Employee("Eng", new BigDecimal("120000.00"), "Ari")));
staff.sort(order);
staff.forEach(e -> System.out.println(e.department() + " " + e.salary() + " " + e.name()));
// Eng 150000 Ama
// Eng 120000.00 Ari
// Eng 120000 Bao
// Eng 120000 null
// Ops 90000 Cy
How each key splits the ties
Employeedepartmentsalary (desc)name (nulls last)
Eng 150000 AmaEngfirst: highestnot needed
Eng 120000.00 AriEngtie at 120000Ari
Eng 120000 BaoEngtie at 120000Bao
Eng 120000 nullEngtie at 120000null, so last
Ops 90000 CyOps, after Engnot needednot 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.

Java
Comparator<Employee> wrong = Comparator
.comparing(Employee::department)
.thenComparing(Employee::salary)
.reversed() // reverses department AND salary
.thenComparing(Employee::name, Comparator.nullsLast(Comparator.naturalOrder()));
// Ops 90000 Cy <- Ops now comes before Eng
// Eng 120000.00 Ari <- and salaries are now low to high
// Eng 120000 Bao
// Eng 120000 null
// Eng 150000 Ama

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.

Java
BigDecimal a = new BigDecimal("10.0");
BigDecimal b = new BigDecimal("10.00");
System.out.println(a.compareTo(b)); // 0: equal for sorting
System.out.println(a.equals(b)); // false: different 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.

Java
Comparator<Employee> bad = (a, b) -> a.salary().intValue() - b.salary().intValue();
// 1. Truncation: intValue() drops the fraction
// 10.90 and 10.10 -> 10 - 10 = 0, treated as equal
// 2. Overflow: the difference of two ints may not fit in an int
int x = Integer.MAX_VALUE, y = -1;
System.out.println(x - y); // -2147483648: wrong sign
System.out.println(Integer.compare(x, y)); // 1: correct
// BigDecimal.intValue() also silently drops high-order bits for very large values

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.

What to say in the interviewAbout 80 seconds aloud

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/