Quick revision
The short answer
For the averages we use employees.stream().collect(Collectors.groupingBy(Employee::department, Collectors.averagingDouble(Employee::salary))). For the names we group with a downstream mapping collector, groupingBy(Employee::department, Collectors.mapping(Employee::name, Collectors.toList())), after sorting the stream by name so each list keeps that encounter order. groupingBy returns a HashMap by default, so we pass TreeMap::new as the map factory if we want sorted keys, and it throws NullPointerException if the classifier returns null.
What to remember
In this answer, we used groupingBy with a classifier and a downstream collector. averagingDouble computed the average salary per department in one pass, and mapping(Employee::name, toList()) collected the names per department, sorted because we sorted the stream by name first and groupingBy keeps encounter order. We saw that the default map is a HashMap with no defined key order, so we pass TreeMap::new for sorted keys, and that a null key from the classifier throws NullPointerException, which we handle by filtering or by mapping to an explicit key.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
For the averages we use employees.stream().collect(Collectors.groupingBy(Employee::department, Collectors.averagingDouble(Employee::salary))). For the names we group with a downstream mapping collector, groupingBy(Employee::department, Collectors.mapping(Employee::name, Collectors.toList())), after sorting the stream by name so each list keeps that encounter order. groupingBy returns a HashMap by default, so we pass TreeMap::new as the map factory if we want sorted keys, and it throws NullPointerException if the classifier returns null.
Why this question is asked
Grouping and aggregating is one of the most common jobs in business code: totals per customer, counts per status, averages per department. Collectors.groupingBy does it in one expression, but its overloads and downstream collectors confuse people, and a few details, such as key order and null keys, cause real bugs. Interviewers use this coding question because it tests whether we can compose collectors rather than write a loop with a map of lists. In this answer, we will recap how groupingBy works, write the average per department, then the sorted names, choose a map type for sorted keys, and finish with the null classifier trap.
1A Quick Recap of groupingBy
Collectors.groupingBy(classifier) takes a function that computes a key for each element, the classifier, and collects the elements into a Map from each key to a List of the elements with that key. The second overload, groupingBy(classifier, downstream), lets us decide what to do with the elements of each group instead of listing them: count them, sum them, average them or map them first. That downstream argument is another collector, applied separately inside each group. The third overload adds a map factory, a supplier that creates the map, between the two.
We will use this sample data throughout.
2Average Salary per Department
The classifier is Employee::department, and the downstream collector is averagingDouble, which takes a function that extracts the number to average.
| Key | Salaries fed downstream | Result |
|---|---|---|
| ENG | 100000, 120000 | 110000.0 |
| OPS | 90000, 80000 | 85000.0 |
Notice how this works inside: for each employee, groupingBy computes the department, finds or creates the averaging state for that key, and feeds the salary into it. averagingDouble keeps a running sum and count per group and divides at the end, so the whole calculation is one pass over the list with no intermediate lists of employees.
3Names per Department, Sorted by Name
For the second map, we want names, not employees, in each group, so we use the downstream collector mapping(Employee::name, toList()), which converts each element before collecting it. To get the names sorted, we sort the stream before grouping. groupingBy adds elements to each group's list in encounter order, the order in which they arrive, so sorting first gives each list sorted order.
Without the sorted step, the lists would follow the input order, ENG=[Bob, Ann] and OPS=[Dee, Cid]. Another way is to sort each group at the end with collectingAndThen(mapping(Employee::name, toList()), l -> l.stream().sorted().toList()), which is useful when the stream itself must stay in a different order. Sorting once up front is simpler and usually cheaper.
4Choosing the Map Type for Sorted Keys
groupingBy creates a HashMap by default, so the order of the departments in the result is not defined. It happens to print ENG before OPS here, but with other keys or more entries the order can change. If we want the departments sorted, we pass TreeMap::new as the map factory, using the three-argument overload.
Notice that the declared type can now be TreeMap, which gives us methods such as firstKey and headMap. If we only want to keep the order in which departments first appear, LinkedHashMap::new is the factory to use.
5The Null Classifier Trap
groupingBy refuses null keys. If any employee has no department, the classifier returns null and the whole collection fails, even though HashMap itself allows a null key.
The fix depends on what a missing department means. If such employees should be ignored, filter them out first with filter(e -> e.department() != null). If they belong in their own group, map the null to an explicit key, such as e -> Objects.requireNonNullElse(e.department(), "UNASSIGNED"). Either way, the decision is visible in the code instead of being an exception in production.
6Follow-up questions
What is the difference between averagingDouble and summarizingDouble?
averagingDouble gives only the average. summarizingDouble gives a DoubleSummaryStatistics per group with count, sum, min, max and average together, computed in the same single pass, which is useful when a report needs several of those numbers.
Does the average of an empty group cause a problem?
groupingBy never creates an empty group, because a key exists only when at least one element maps to it. If we do average an empty stream with averagingDouble, the result is 0.0, not NaN or an exception, which is worth knowing for other uses.
Can we group by two keys at once?
Yes, either by nesting, groupingBy(Employee::department, groupingBy(Employee::level)), which gives a map of maps, or by using a record as a composite key, groupingBy(e -> new DeptLevel(e.department(), e.level())), which gives a flat map and is often easier to read.
7Conclusion
In this answer, we used groupingBy with a classifier and a downstream collector. averagingDouble computed the average salary per department in one pass, and mapping(Employee::name, toList()) collected the names per department, sorted because we sorted the stream by name first and groupingBy keeps encounter order. We saw that the default map is a HashMap with no defined key order, so we pass TreeMap::new for sorted keys, and that a null key from the classifier throws NullPointerException, which we handle by filtering or by mapping to an explicit key.
Open with
For the averages I'd write employees stream collect groupingBy with Employee::department as the classifier and averagingDouble of Employee::salary as the downstream collector. groupingBy computes the key for each employee, and the downstream collector runs separately inside each group, so averagingDouble keeps a running sum and count per department and divides at the end, all in one pass.
Then, if they want more
For the names I'd use groupingBy again with a mapping downstream collector: mapping Employee::name into toList. To get each list sorted, I sort the stream first with sorted by Comparator comparing Employee::name. groupingBy adds elements in encounter order, so each department's list comes out sorted. Alternatively, collectingAndThen can sort each list at the end. Two details I'd mention.
First, groupingBy returns a HashMap by default, so the order of departments isn't defined; if I want sorted keys, I use the three-argument version with TreeMap::new as the map factory, or LinkedHashMap::new to keep first-seen order.
Second, groupingBy throws a NullPointerException, element cannot be mapped to a null key, if the classifier returns null, so if department can be missing I either filter those employees out first or map null to an explicit key like UNASSIGNED.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.stream, package documentation, java.util.function, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Given List<Employee> with department() and salary(), write code that returns Map<String...": https://scrivio-interview-library.netlify.app/java/streams/92994efc62/