Interview Q&A / Java

IntermediateQuick answerCoding1 min readUpdated 3 Oct 2026

Write Java code to sort employees by salary (highest first) and then by name.

SHORT ANSWER

Build a Comparator with Comparator.comparingDouble(Employee::salary).reversed().thenComparing(Employee::name) and pass it to list.sort. Sorting costs O(n log n) time.

Explain it simply

We need two rules: higher salary comes first, and when salaries tie, names go in A to Z order. A Comparator chain expresses that directly.

Line by line

java
import java.util.*;

record Employee(String name, double salary) {}

public class SortDemo {
    public static void main(String[] args) {
        List<Employee> staff = new ArrayList<>(List.of(
            new Employee("Meera", 50000),
            new Employee("Arjun", 70000),
            new Employee("Bhavna", 50000)));

        staff.sort(Comparator.comparingDouble(Employee::salary).reversed()
                             .thenComparing(Employee::name));

        for (Employee e : staff) System.out.println(e.name() + " " + e.salary());
        // prints:
        // Arjun 70000.0
        // Bhavna 50000.0
        // Meera 50000.0
    }
}

comparingDouble sorts by salary ascending, reversed() flips it, and thenComparing is consulted only for ties. Use a method reference, not a lambda, before .reversed() so that Java can infer the type.

Complexity

Time O(n log n), space O(n) for the sort's working storage.

What to say in the interview

"I chain comparators: primary key reversed, then a tie-breaker. List.sort uses a stable merge-style sort, so equal elements keep their relative order. Record is only to keep the example short; a normal class with getters works the same way."

Common mistakes

  • Subtracting salaries inside compare. It breaks with doubles and overflows with ints.

#java#collections#comparator

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.