Java 8: Find the second highest salary in each department. Show sorting, streams and the optimal single pass.
Problem
Given employees with department and salary, return each department's second highest distinct salary (absent if the department has fewer than two distinct salaries). This is a Java 8 favourite and a SQL favourite.
final class Staff {
final String name, dept;
final long salary;
Staff(String name, String dept, long salary) { this.name = name; this.dept = dept; this.salary = salary; }
}Approach 1: Group, then sort each department (O(n log n))
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
class SecondSort {
static Map<String, Long> find(List<Staff> staff) {
Map<String, List<Long>> byDept = new HashMap<>();
for (Staff s : staff) byDept.computeIfAbsent(s.dept, k -> new ArrayList<>()).add(s.salary);
Map<String, Long> result = new HashMap<>();
for (Map.Entry<String, List<Long>> e : byDept.entrySet()) {
List<Long> distinct = new ArrayList<>(new TreeSet<>(e.getValue())); // sorted, distinct
Collections.reverse(distinct);
if (distinct.size() >= 2) result.put(e.getKey(), distinct.get(1));
}
return result;
}
}Approach 2: Streams with groupingBy + collectingAndThen (O(n log n))
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
class SecondStreams {
static Map<String, Optional<Long>> find(List<Staff> staff) {
return staff.stream().collect(Collectors.groupingBy(s -> s.dept,
Collectors.collectingAndThen(Collectors.toList(), list -> list.stream()
.map(s -> s.salary).distinct()
.sorted(Comparator.reverseOrder())
.skip(1).findFirst())));
}
}Approach 3: TreeSet per department (O(n log d), handy if you need top-N later)
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
class SecondTreeSet {
static Map<String, Long> find(List<Staff> staff) {
Map<String, TreeSet<Long>> sets = new HashMap<>();
for (Staff s : staff) sets.computeIfAbsent(s.dept, k -> new TreeSet<>()).add(s.salary);
Map<String, Long> result = new HashMap<>();
sets.forEach((dept, set) -> {
Long top = set.last();
Long second = set.lower(top); // greatest value strictly below the top
if (second != null) result.put(dept, second);
});
return result;
}
}Approach 4: Single pass with two trackers per department (O(n), optimal)
Keep only the top two distinct salaries for each department, updating them as you go: no sorting at all.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class SecondSinglePass {
static Map<String, Long> find(List<Staff> staff) {
Map<String, long[]> top2 = new HashMap<>(); // [highest, second], Long.MIN_VALUE = none
for (Staff s : staff) {
long[] t = top2.computeIfAbsent(s.dept, k -> new long[] {Long.MIN_VALUE, Long.MIN_VALUE});
if (s.salary > t[0]) { t[1] = t[0]; t[0] = s.salary; }
else if (s.salary < t[0] && s.salary > t[1]) t[1] = s.salary; // ignore duplicates of the top
}
Map<String, Long> result = new HashMap<>();
top2.forEach((dept, t) -> { if (t[1] != Long.MIN_VALUE) result.put(dept, t[1]); });
return result;
}
}
class SecondDemo {
public static void main(String[] args) {
List<Staff> staff = java.util.Arrays.asList(
new Staff("A", "Eng", 300), new Staff("B", "Eng", 300), new Staff("C", "Eng", 250), new Staff("D", "Eng", 100),
new Staff("E", "Ops", 90), new Staff("F", "HR", 80), new Staff("G", "HR", 80));
System.out.println(new java.util.TreeMap<>(SecondSort.find(staff))); // {Eng=250}
System.out.println(new java.util.TreeMap<>(SecondStreams.find(staff))); // {Eng=Optional[250], HR=Optional.empty, Ops=Optional.empty}
System.out.println(new java.util.TreeMap<>(SecondTreeSet.find(staff))); // {Eng=250}
System.out.println(new java.util.TreeMap<>(SecondSinglePass.find(staff))); // {Eng=250}
}
}Feasible → optimal
- Sort per department or streams with
sorted().skip(1): O(n log n), most readable. TreeSetper department: O(n log d), extends naturally to "top N".- Single pass with two trackers: O(n) time, O(departments) memory: optimal.
Note the trap: "second highest" usually means second distinct salary, so
distinct()(or ignoring ties with the top) matters.
Follow-up questions interviewers ask
Try answering each one before you open it.
Write it in SQL.
With a window function: SELECT dept, salary FROM (SELECT dept, salary, DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS r FROM employee) t WHERE r = 2;. DENSE_RANK gives tied salaries the same rank, matching "second highest distinct". Without window functions: SELECT dept, MAX(salary) FROM employee e WHERE salary < (SELECT MAX(salary) FROM employee WHERE dept = e.dept) GROUP BY dept;.
How would you return the employee names instead of just the salary?
Two passes: compute the second-highest distinct salary per department (any approach above), then filter employees whose salary equals their department's value and group their names with groupingBy(dept, mapping(name, toList())). Ties produce several names, which is usually what the business wants.