Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Write a Comparator that sorts employees by department ascending, then salary descending, then name, with nulls in department sorted last.

We build the comparator as a chain: Comparator.comparing(Employee::department, Comparator.nullsLast(Comparator.naturalOrder())) sorts by department with nulls last, .thenComparing(Comparator.comparingInt(Employee::salary).reversed()) sorts by salary descending without boxing, and .thenComparing(Employee::name) breaks the remaining ties. The common mistake is calling reversed() on the chain, which reverses every key before it, and since comparators are stateless we store the result in a constant.

Why this question is asked

Multi-key sorting comes up constantly in real code: reports, tables in a UI, export files and paginated APIs all need a precise order. Since Java 8, Comparator has factory and chaining methods that make such orders short and readable, but they have a few traps around reversing, nulls and boxing. Interviewers ask this coding question because a correct answer shows that we know what each method in the chain applies to. In this answer, we will recap how comparator chains work, build the comparator one key at a time, check its output on sample data, look at the reversed() mistake, and finish with performance and reuse.

1A Quick Recap of Comparator Chains

A Comparator<T> compares two objects and returns a negative number, zero or a positive number when the first is smaller, equal or larger. Comparator.comparing(keyExtractor) builds one from a function that extracts a sort key, such as Employee::department. thenComparing adds a second comparator that is used only when the first one says two objects are equal, so each key acts as a tie-breaker for the keys before it.

Each key can have its own order. comparing and thenComparing accept an optional second argument, a comparator for the key itself, such as Comparator.reverseOrder() or Comparator.nullsLast(...). That is how we give one key a different direction or null handling without affecting the others. We will use this record:

Java
record Employee(String name, String department, int salary) {}

2Building the Comparator Key by Key

Here is the full comparator, with each key on its own line.

Java
static final Comparator<Employee> BY_DEPT_SALARY_NAME =
Comparator.comparing(Employee::department,
Comparator.nullsLast(Comparator.naturalOrder())) // 1: department, nulls last
.thenComparing(Comparator.comparingInt(Employee::salary)
.reversed()) // 2: salary, highest first
.thenComparing(Employee::name); // 3: name, A to Z

The first key extracts the department and compares it with nullsLast(naturalOrder()). naturalOrder() compares Strings alphabetically, and nullsLast wraps it so that a null department is treated as larger than any value, which puts those employees at the end. Without the wrapper, comparing a null department would throw NullPointerException.

The second key is a complete comparator of its own: comparingInt(Employee::salary) compares salaries as primitive ints, and reversed() flips only that comparator, so higher salaries come first. thenComparing uses it only among employees in the same department. An equivalent form is .thenComparing(Employee::salary, Comparator.reverseOrder()), which reads well but boxes each int into an Integer for every comparison. The third key sorts by name when department and salary are both equal.

3Checking the Result on Sample Data

Let us sort six employees and check each position against the rules.

Java
List<Employee> staff = new ArrayList<>(List.of(
new Employee("Ana", "Sales", 5000), new Employee("Bo", "IT", 7000),
new Employee("Cy", "IT", 7000), new Employee("Di", null, 9000),
new Employee("Ed", "IT", 6000), new Employee("Fay", "Sales", 8000)));
staff.sort(BY_DEPT_SALARY_NAME);
staff.stream().map(Employee::name).toList(); // [Bo, Cy, Ed, Fay, Ana, Di]
Why each employee lands where it does
PositionEmployeeDecided by
1Bo, IT, 7000IT first; highest IT salary; Bo before Cy by name
2Cy, IT, 7000same department and salary as Bo; name decides
3Ed, IT, 6000lower salary within IT
4Fay, Sales, 8000Sales after IT; higher salary first
5Ana, Sales, 5000lower salary within Sales
6Di, null, 9000null department sorts last, whatever the salary
Each key only matters when all keys before it are equal.

IT comes before Sales alphabetically, and Di, whose department is null, is last even though she has the highest salary, because the department key decides first. Within IT, the 7000 salaries come before 6000, and Bo comes before Cy because the name key breaks their tie.

4The reversed() Mistake

A natural-looking way to write "salary descending" is to add the salary key and then call reversed(). But reversed() applies to the whole comparator it is called on, which at that point is the chain built so far, so it also reverses the department.

Java
Comparator<Employee> wrong =
Comparator.comparing(Employee::department, Comparator.nullsLast(Comparator.naturalOrder()))
.thenComparingInt(Employee::salary)
.reversed() // reverses department AND salary
.thenComparing(Employee::name);
staff.sort(wrong);
staff.stream().map(Employee::name).toList(); // [Di, Fay, Ana, Bo, Cy, Ed]

Notice what happened: departments are now in reverse alphabetical order, and the null department, which nullsLast put last, is now first, because reversing the whole order also reverses where the nulls go. The fix is what we did earlier: reverse only the salary comparator, inside the thenComparing call. A useful habit is to read each reversed() as "reverse everything to my left".

5Primitive Keys, Type Inference and Constants

For int, long and double keys, comparingInt, comparingLong and comparingDouble, and the matching thenComparingInt and friends, compare primitives directly. The generic comparing(Employee::salary) works but boxes every value into an Integer on each comparison, which adds garbage when sorting large lists.

One more trap is type inference. Comparator.comparing(e -> e.salary()).reversed() often fails to compile, because Java cannot infer the lambda's type before reversed() is called; method references such as Employee::salary, or an explicit type, as in comparing((Employee e) -> e.salary()), avoid it.

Finally, comparators built this way hold no state; they only describe an order. So they are thread-safe and can be created once and stored as static final constants, as we did, rather than rebuilt in every method. A named constant such as BY_DEPT_SALARY_NAME also documents the business rule.

6Follow-up questions

How would you also handle a null name or a null employee?

Wrap the name key in the same way, .thenComparing(Employee::name, Comparator.nullsLast(Comparator.naturalOrder())), and wrap the whole comparator with Comparator.nullsLast(BY_DEPT_SALARY_NAME) if the list itself may contain null elements.

Is List.sort stable, and does it matter here?

Yes, List.sort and Collections.sort are stable: equal elements keep their original order. With our three keys, two employees compare as equal only if they share department, salary and name, so stability rarely matters, but adding a unique key such as an ID as the last tie-breaker makes the order fully deterministic.

Can the same comparator be used in a stream?

Yes: staff.stream().sorted(BY_DEPT_SALARY_NAME).toList() gives the same order, and the comparator can also drive a TreeMap or a PriorityQueue. Being a constant makes that reuse natural.

7Conclusion

In this answer, we built a three-key comparator: comparing with nullsLast(naturalOrder()) for the department, thenComparing with comparingInt(...).reversed() for salary descending without boxing, and thenComparing for the name. We checked its output on sample data, saw that calling reversed() on the chain reverses every earlier key and even moves the nulls, and stored the stateless comparator as a constant.

What to say in the interviewAbout 60 seconds aloud

Open with

I would write it as a chain stored in a constant. First, Comparator.comparing(Employee::department, Comparator.nullsLast(Comparator.naturalOrder())), so departments are alphabetical and employees with a null department go to the end instead of throwing a NullPointerException.

Then, if they want more

Then thenComparing with Comparator.comparingInt(Employee::salary).reversed(), so within a department the highest salary comes first; I use comparingInt to avoid boxing, and the reversed() is applied only to that inner comparator. The answer-key form thenComparing(Employee::salary, Comparator.reverseOrder()) is also correct, it just boxes. Then thenComparing(Employee::name) for ties.

The classic mistake is writing thenComparingInt(salary) and then calling reversed() on the chain, because reversed reverses everything before it, so the departments come out reversed and the null departments jump to the front. I would also use method references rather than lambdas so type inference works with reversed().

And because comparators are stateless and thread-safe, I store it as a static final constant with a name that describes the business rule.

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 documentation below. 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 that sorts employees by department ascending, then salary descending...": https://scrivio-interview-library.netlify.app/java/object-contracts/d447cdeb11/