Write Java code to sort employees by salary (highest first) and then by name.
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
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.