Java 8 Streams interview problems on an Employee list.
Problem
Given List<Employee> with name, department, salary, age, gender and joining date, answer the classic questions asked in Java interviews with streams.
java
import java.time.LocalDate;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;
record Employee(String name, String dept, double salary, int age, String gender, LocalDate joined) {}
class EmployeeStreams {
public static void main(String[] args) {
List<Employee> emps = List.of(
new Employee("Asha", "Engineering", 220_000, 34, "F", LocalDate.of(2016, 3, 1)),
new Employee("Ravi", "Engineering", 180_000, 29, "M", LocalDate.of(2019, 7, 15)),
new Employee("Meera", "Finance", 150_000, 41, "F", LocalDate.of(2012, 1, 9)),
new Employee("John", "Finance", 150_000, 38, "M", LocalDate.of(2015, 5, 20)),
new Employee("Karan", "HR", 90_000, 26, "M", LocalDate.of(2022, 2, 1)));
// 1. Count employees per department
Map<String, Long> countByDept = emps.stream()
.collect(Collectors.groupingBy(Employee::dept, TreeMap::new, Collectors.counting()));
// 2. Average salary per department
Map<String, Double> avgSalary = emps.stream()
.collect(Collectors.groupingBy(Employee::dept, TreeMap::new, Collectors.averagingDouble(Employee::salary)));
// 3. Highest paid employee in each department
Map<String, Optional<Employee>> topPaid = emps.stream()
.collect(Collectors.groupingBy(Employee::dept, TreeMap::new,
Collectors.maxBy(Comparator.comparingDouble(Employee::salary))));
// 4. Second highest distinct salary
Optional<Double> secondHighest = emps.stream()
.map(Employee::salary).distinct()
.sorted(Comparator.reverseOrder())
.skip(1).findFirst();
// 5. Names of employees who joined before 2016, sorted
List<String> veterans = emps.stream()
.filter(e -> e.joined().isBefore(LocalDate.of(2016, 1, 1)))
.map(Employee::name).sorted().toList();
// 6. Partition by salary above 150k
Map<Boolean, List<String>> partition = emps.stream()
.collect(Collectors.partitioningBy(e -> e.salary() > 150_000,
Collectors.mapping(Employee::name, Collectors.toList())));
// 7. Salary statistics in one pass
DoubleSummaryStatistics stats = emps.stream().mapToDouble(Employee::salary).summaryStatistics();
// 8. Department with the highest total salary
String costliestDept = emps.stream()
.collect(Collectors.groupingBy(Employee::dept, Collectors.summingDouble(Employee::salary)))
.entrySet().stream().max(Map.Entry.comparingByValue()).map(Map.Entry::getKey).orElseThrow();
// 9. Comma-separated names by gender
Map<String, String> namesByGender = emps.stream()
.collect(Collectors.groupingBy(Employee::gender, TreeMap::new,
Collectors.mapping(Employee::name, Collectors.joining(", "))));
// 10. Sort by salary descending, then name
List<String> ranked = emps.stream()
.sorted(Comparator.comparingDouble(Employee::salary).reversed().thenComparing(Employee::name))
.map(Employee::name).toList();
System.out.println(countByDept); // {Engineering=2, Finance=2, HR=1}
System.out.println(avgSalary); // {Engineering=200000.0, Finance=150000.0, HR=90000.0}
System.out.println(topPaid.get("Engineering").map(Employee::name).orElse("-")); // Asha
System.out.println(secondHighest.orElse(0.0)); // 180000.0
System.out.println(veterans); // [John, Meera]
System.out.println(partition); // {false=[Meera, John, Karan], true=[Asha, Ravi]}
System.out.println(stats.getMax() + " " + stats.getAverage());
System.out.println(costliestDept); // Engineering
System.out.println(namesByGender); // {F=Asha, Meera, M=Ravi, John, Karan}
System.out.println(ranked); // [Asha, Ravi, John, Meera, Karan]
}
}Key points to mention
groupingBytakes an optional map factory (TreeMap::newfor sorted keys) and a downstream collector (counting,averagingDouble,maxBy,mapping,joining,summingDouble).maxByreturnsOptionalper group because a group could theoretically be empty; usecollectingAndThen(maxBy(...), Optional::get)to unwrap.distinct()beforeskip(1)matters for "second highest distinct salary".- Prefer primitive streams (
mapToDouble) for numeric aggregations.
Follow-up questions interviewers ask
Try answering each one before you open it.
How do you get the highest paid employee per department without Optional in the map?
java
Map<String, Employee> top = emps.stream().collect(Collectors.toMap(
Employee::dept, e -> e,
BinaryOperator.maxBy(Comparator.comparingDouble(Employee::salary))));toMap with a merge function keeps the higher-paid employee when two share a department key. Alternatively collectingAndThen(maxBy(...), Optional::get) inside groupingBy.
What is the difference between Collectors.toList() and Stream.toList()?
Stream.toList() (Java 16) returns an unmodifiable list and allows nulls. Collectors.toList() returns a list with no guaranteed type or mutability (an ArrayList in practice, so code often relies on mutating it). Use Collectors.toCollection(ArrayList::new) when you need a mutable list explicitly.