You’ve solved 25 problems with loops. That was on purpose. Streams are much easier to learn when you already know what the code must do, because then you only need to learn how to say it.
Almost every Java interview has a stream round, and it almost always uses an Employee list. We’ll use the same one from Phase 5:
record Employee(String name, String department, int age, double salary) {}
List<Employee> employees = 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)
);
How a stream works, in three parts
employees.stream() // 1. source: where the elements come from
.filter(e -> e.age() > 30) // 2. intermediate operations: transform, 0 or more
.map(Employee::name)
.toList(); // 3. terminal operation: produce a result, exactly 1
- Source:
list.stream(),Arrays.stream(array),Stream.of(a, b, c). - Intermediate operations like
filter,mapandsortedeach return a new stream. They’re lazy: they don’t run when you write them. - A terminal operation like
toList,collect,countorforEachpulls the elements through the whole pipeline. Only now does anything happen.
A stream doesn’t change the original list. And once a stream has run, it’s used up; you need a new .stream() to go again.
26. Find employees with salary above 10 lakh
filter keeps the elements for which your test returns true.
List<Employee> highEarners = employees.stream()
.filter(e -> e.salary() > 1_000_000)
.toList();
Asha, Ravi, Priya, Kiran, Arjun
The loop version, for comparison:
List<Employee> highEarners = new ArrayList<>();
for (Employee e : employees) {
if (e.salary() > 1_000_000) highEarners.add(e);
}
The if became filter, and the add became toList().
toList() or collect(Collectors.toList())? stream.toList() was added in Java 16 and returns a list you can’t change. collect(Collectors.toList()) works on Java 8 and gives you a normal ArrayList in practice. If your interview is on Java 8, or you need to add to the result later, use collect(Collectors.toList()).
27. Get the employee names
map turns each element into something else. Here: each Employee becomes a String.
List<String> names = employees.stream()
.map(Employee::name)
.toList();
// [Asha, Ravi, Meena, John, Priya, Kiran, Fatima, Arjun]
Combine it with problem 26:
List<String> highEarnerNames = employees.stream()
.filter(e -> e.salary() > 1_000_000)
.map(Employee::name)
.map(String::toUpperCase)
.collect(Collectors.toList());
// [ASHA, RAVI, PRIYA, KIRAN, ARJUN]
Order matters. filter must come before map(Employee::name), because after that map you have strings, and a string has no salary.
28. Sort employees by salary
sorted takes the same comparators you built in Phase 5.
List<Employee> bySalary = employees.stream()
.sorted(Comparator.comparingDouble(Employee::salary))
.toList();
Fatima 650000.0
John 700000.0
Meena 900000.0
Ravi 1200000.0
Priya 1200000.0
Kiran 1500000.0
Asha 1800000.0
Arjun 2100000.0
Unlike list.sort(...), this does not change employees. It returns a new, sorted list. (That’s also why it works on our List.of(...), which can’t be changed.)
29. Get the top 3 highest-paid employees
Sort high to low, then limit(3) keeps only the first three.
List<Employee> top3 = employees.stream()
.sorted(Comparator.comparingDouble(Employee::salary).reversed())
.limit(3)
.toList();
Arjun 2100000.0
Asha 1800000.0
Kiran 1500000.0
Want just the names? Add .map(Employee::name) after limit. That’s the pipeline in the picture at the top of this page.
skip(n) is the opposite of limit: it drops the first n elements. You’ll use it for “second highest salary” in Phase 8.
30. Calculate the average salary
double avg = employees.stream()
.mapToDouble(Employee::salary)
.average()
.orElse(0.0);
// 1256250.0
Two new ideas:
mapToDoubleturns the stream into aDoubleStream, a stream of plaindoublenumbers. Number streams have maths methods built in:sum(),average(),min(),max(). A normalStream<Double>doesn’t. (There’s alsomapToIntandmapToLong.)average()returns anOptionalDouble, not adouble. Why? The average of an empty list isn’t 0, it doesn’t exist. TheOptionalmakes you decide what to do:.orElse(0.0)says “use 0 if the list was empty”.
Bonus: need the count, sum, min, max and average? One pass does it all:
DoubleSummaryStatistics stats = employees.stream()
.mapToDouble(Employee::salary)
.summaryStatistics();
// count=8, sum=10050000, min=650000, average=1256250, max=2100000
31. Group employees by department
This is where streams start to save real work. Collectors.groupingBy sorts elements into buckets by a key, and returns a Map.
Map<String, List<Employee>> byDept = employees.stream()
.collect(Collectors.groupingBy(Employee::department));
Engineering -> [Asha, Ravi, Priya]
Sales -> [John, Kiran]
Finance -> [Arjun]
HR -> [Meena, Fatima]
Compare with the loop from Phase 4:
Map<String, List<Employee>> byDept = new HashMap<>();
for (Employee e : employees) {
byDept.computeIfAbsent(e.department(), k -> new ArrayList<>()).add(e);
}
groupingBy is that computeIfAbsent loop in one line.
Only the names, sorted by department? groupingBy takes two more optional arguments: which map to build, and what to do with each bucket.
Map<String, List<String>> namesByDept = employees.stream()
.collect(Collectors.groupingBy(
Employee::department, // the key
TreeMap::new, // sorted by department
Collectors.mapping(Employee::name, Collectors.toList()) // what each bucket holds
));
// {Engineering=[Asha, Ravi, Priya], Finance=[Arjun], HR=[Meena, Fatima], Sales=[John, Kiran]}
That third argument is called a downstream collector, and it’s the key to most of Phase 8.
32. Find the highest salary in each department
The most asked stream question of them all.
Map<String, Optional<Employee>> topByDept = employees.stream()
.collect(Collectors.groupingBy(
Employee::department,
Collectors.maxBy(Comparator.comparingDouble(Employee::salary))
));
Engineering -> Asha
Sales -> Kiran
Finance -> Arjun
HR -> Meena
Read it as: “group by department, and inside each group, keep the one with the max salary”.
Why Optional<Employee>? maxBy returns an Optional because, in general, a group could be empty. With groupingBy, a group only exists if it has at least one employee, so the Optional is always full here. It’s still awkward to work with, so interviewers often ask: “Can you return Map<String, Employee> instead?”
Unwrap the Optional with collectingAndThen
collectingAndThen runs a collector, then applies one more function to its result:
Map<String, Employee> topByDept = employees.stream()
.collect(Collectors.groupingBy(
Employee::department,
TreeMap::new,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparingDouble(Employee::salary)),
Optional::get
)
));
// {Engineering=Asha, Finance=Arjun, HR=Meena, Sales=Kiran}
Optional::get is safe here for the reason above: every group has at least one employee.
Or use toMap with a merge function
Map<String, Employee> topByDept = employees.stream()
.collect(Collectors.toMap(
Employee::department, // key
Function.identity(), // value: the employee
BinaryOperator.maxBy(Comparator.comparingDouble(Employee::salary)) // on a clash, keep the richer one
));
When two employees have the same department key, toMap calls the third argument to decide which one to keep. BinaryOperator.maxBy keeps the bigger one. No Optional at all. Knowing both versions is a strong answer.
The stream shapes you just used
| Want | Write |
|---|---|
| keep some | .filter(e -> ...) |
| change each | .map(...), .mapToDouble(...) |
| order them | .sorted(comparator) |
| first N / skip N | .limit(n), .skip(n) |
| a list | .toList(), .collect(Collectors.toList()) |
| a number | .count(), .sum(), .average(), .max(...) |
| buckets | .collect(Collectors.groupingBy(key)) |
| one answer per bucket | .collect(Collectors.groupingBy(key, downstream)) |
Next: Phase 8, advanced stream interview puzzles: 18 trickier questions that combine everything, from “second highest salary” to partitioningBy, flatMap and the toMap duplicate-key trap.
Comments