In Phase 3 you sorted a list of numbers. Numbers know how to compare themselves: 3 is less than 5. But how does Java know whether one employee comes before another? By salary? By name? By age?
It doesn’t, until you tell it. That’s what a Comparator is: a rule for ordering two objects.
The Employee we’ll use from now on
Phases 5, 7 and 8 all use the same small list of employees:
record Employee(String name, String department, int age, double salary) {}
List<Employee> employees = new ArrayList<>(List.of(
new Employee("Asha", "Engineering", 29, 1_800_000),
new Employee("Ravi", "Engineering", 35, 1_200_000),
new Employee("Meena", "HR", 41, 900_000),
new Employee("John", "Sales", 26, 700_000),
new Employee("Priya", "Engineering", 26, 1_200_000),
new Employee("Kiran", "Sales", 38, 1_500_000),
new Employee("Fatima", "HR", 30, 650_000),
new Employee("Arjun", "Finance", 45, 2_100_000)
));
A record (Java 16+) is a short way to write a class that just holds data. Java creates the constructor, the getters name(), salary() and so on, plus equals, hashCode and toString. The underscores in 1_800_000 are just for reading; Java ignores them. Salaries are in rupees, so 1_800_000 is 18 lakh.
If your interviewer expects a normal class, it’s this, and every example below works the same with Employee::getSalary instead of Employee::salary:
class Employee {
private final String name;
private final String department;
private final int age;
private final double salary;
Employee(String name, String department, int age, double salary) {
this.name = name;
this.department = department;
this.age = age;
this.salary = salary;
}
public String getName() { return name; }
public String getDepartment() { return department; }
public int getAge() { return age; }
public double getSalary() { return salary; }
}
Notice Ravi and Priya both earn 12 lakh. That tie is on purpose.
How a Comparator thinks
A comparator answers one question about two objects, a and b: which comes first?
int compare(Employee a, Employee b)
- a negative number means
acomes first - zero means they’re equal for this rule (a tie)
- a positive number means
bcomes first
You almost never write compare by hand in modern Java. You build comparators from small pieces instead, and that’s what the next four problems practise.
19. Sort employees by salary
employees.sort(Comparator.comparing(Employee::salary));
Read it as: “sort the employees, comparing them by salary”. Employee::salary is a method reference: a short way to write the lambda e -> e.salary().
Fatima 650,000
John 700,000
Meena 900,000
Ravi 1,200,000
Priya 1,200,000
Kiran 1,500,000
Asha 1,800,000
Arjun 2,100,000
Low to high is the default. Ravi comes before Priya only because he was before her in the original list. Java’s sort is stable: when two elements tie, they keep their original order.
For a double, int or long field, the primitive versions avoid boxing every number into an object, and they’re what experienced developers write:
employees.sort(Comparator.comparingDouble(Employee::salary));
The old way, for comparison
Before Java 8 you’d write an anonymous class:
Collections.sort(employees, new Comparator<Employee>() {
@Override
public int compare(Employee a, Employee b) {
return Double.compare(a.salary(), b.salary());
}
});
Same result, eight lines instead of one. If you write (int) (a.salary() - b.salary()), stop: subtracting can overflow for big numbers, and casting a double to int loses the fraction. Double.compare and Integer.compare are always safe.
20. Sort by salary, descending
Add .reversed():
employees.sort(Comparator.comparingDouble(Employee::salary).reversed());
Arjun 2,100,000
Asha 1,800,000
Kiran 1,500,000
Ravi 1,200,000
Priya 1,200,000
Meena 900,000
John 700,000
Fatima 650,000
The lambda trap
This looks the same, but it doesn’t compile:
employees.sort(Comparator.comparing(e -> e.salary()).reversed());
// error: cannot find symbol salary()
Why? When you add .reversed(), Java can no longer work out that e is an Employee, so it treats it as Object, which has no salary(). Fix it with a method reference (Employee::salary), or by naming the type: (Employee e) -> e.salary(). Interviewers like this question because it shows whether you’ve actually written Comparator code.
21. Sort by salary, then by age
Problem: sort by salary, highest first. When two people earn the same, put the younger one first.
employees.sort(
Comparator.comparingDouble(Employee::salary).reversed()
.thenComparingInt(Employee::age)
);
Arjun 45 2,100,000
Asha 29 1,800,000
Kiran 38 1,500,000
Priya 26 1,200,000 ← tie on salary,
Ravi 35 1,200,000 ← so the younger one goes first
Meena 41 900,000
John 26 700,000
Fatima 30 650,000
How it works: thenComparing is only asked when the first comparator returns 0, a tie. Priya and Ravi tie on salary, so the age rule decides. For everyone else, salary already decided and age is never looked at.
Watch where .reversed() goes. It reverses everything before it in the chain. So:
comparingDouble(Employee::salary).reversed().thenComparingInt(Employee::age)
// salary high → low, then age low → high ✓ what we want
comparingDouble(Employee::salary).thenComparingInt(Employee::age).reversed()
// salary high → low, then age HIGH → LOW the reversed() flipped both
To reverse only one key in the middle of a chain, pass a second comparator:
// by department A→Z, then salary high→low inside each department
employees.sort(
Comparator.comparing(Employee::department)
.thenComparing(Employee::salary, Comparator.reverseOrder())
);
Comparable vs Comparator
A very common theory question that fits here:
Comparable |
Comparator |
|
|---|---|---|
| Where | inside the class: class Employee implements Comparable<Employee> |
outside, a separate object |
| Method | compareTo(Employee other) |
compare(Employee a, Employee b) |
| How many orders | one, the “natural” order | as many as you like |
| Used by | Collections.sort(list), TreeSet with no arguments |
list.sort(comparator), new TreeSet<>(comparator) |
String and Integer implement Comparable, which is why Collections.sort worked on them in Phase 3 without any comparator.
22. Sort a Map by value
Problem: you have the word counts from problem 16. Print them from the most frequent to the least.
java=3
spring=2
kafka=1
A HashMap has no order, and a TreeMap sorts by key, not value. So you sort the map’s entries and put them into a map that keeps order: a LinkedHashMap.
Map<String, Integer> counts = Map.of("java", 3, "spring", 2, "kafka", 1);
Map<String, Integer> sorted = counts.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(a, b) -> a,
LinkedHashMap::new
));
System.out.println(sorted); // {java=3, spring=2, kafka=1}
It’s a lot at once, so line by line:
entrySet().stream(): a stream of key-value pairs.sorted(Map.Entry.comparingByValue().reversed()): sort the pairs by value, high to low. The<String, Integer>tells Java the types, for the same reason as the lambda trap in problem 20:.reversed()stops Java from working them out.collect(Collectors.toMap(...)): put the pairs back into a map. It takes four arguments:- how to get the key:
Map.Entry::getKey - how to get the value:
Map.Entry::getValue - what to do if two keys clash:
(a, b) -> a(they can’t here, but this version oftoMapneeds it) - which map to build:
LinkedHashMap::new
- how to get the key:
That last argument is the one everyone forgets. Without it, toMap builds a plain HashMap, which throws your careful sort away:
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// {spring=2, java=3, kafka=1} order lost!
Break ties too: if spring and docker both have 2, sort them by name so the output is always the same:
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()))
Without streams
If streams aren’t allowed yet, copy the entries into a list, sort the list, and copy back:
List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());
entries.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue())); // high → low
Map<String, Integer> sorted = new LinkedHashMap<>();
for (Map.Entry<String, Integer> e : entries) {
sorted.put(e.getKey(), e.getValue());
}
e2 before e1 in the lambda is what makes it descending.
Cost: O(n log n) for n entries, because of the sort.
What you practised
- What a
Comparatorreturns, and that you rarely write one by hand Comparator.comparing,comparingDoubleandcomparingInt.reversed(), and that it flips everything before itthenComparingfor tie-breakersComparablevsComparator- Sorting a map by value with
comparingByValueandtoMap(..., LinkedHashMap::new)
Next: Phase 6, stack and queue interview programs: valid parentheses, reversing a queue and generating binary numbers.
Comments