← Java roadmap

Topic 28 of 30 · Advanced

Compute department averages with collectors

Return average integer salary per department without mutating the input list.

AdvancedMid-level · 3–5 yearsStreams

Java 17+; compile each complete program as Main.java.

Problem statement

Return average integer salary per department without mutating the input list.

Build a deterministic department summary at display time.

Input: List of Employee records; non-null dept.

Output: Map dept to Double average; sorted only for display.

  • No missing departments or salaries.
  • Empty input yields an empty map.

Sample 1

Input: IT:100,80; HR:60
Output: {HR=60.0, IT=90.0}

IT average is 90.

Sample 2

Input: empty
Output: {}

No departments are manufactured.

Brute-force solution

For each distinct department rescan every employee to sum/count.

O(n) expected grouping; sorted display O(g log g).

import java.util.*;
import java.util.stream.*;
class Main {
record Employee(String dept,int salary){}
static Map<String,Double> averages(List<Employee> rows){return rows.stream().collect(Collectors.groupingBy(Employee::dept,Collectors.averagingInt(Employee::salary)));}
public static void main(String[] args) throws Exception {
Map<String,Double> out=averages(List.of(new Employee("IT",100),new Employee("IT",80),new Employee("HR",60)));
System.out.println(new TreeMap<>(out));
if(out.get("IT")!=90.0 || out.get("HR")!=60.0)throw new AssertionError();
}
}
Optimized solution

groupingBy plus averagingInt accumulates a summary per group in one sequential traversal.

  1. Group on dept.
  2. Accumulate salaries using averagingInt.
  3. Sort keys only when displaying.
import java.util.*;
import java.util.stream.*;
class Main {
record Employee(String dept,int salary){}
static Map<String,Double> averages(List<Employee> rows){return rows.stream().collect(Collectors.groupingBy(Employee::dept,Collectors.averagingInt(Employee::salary)));}
public static void main(String[] args) throws Exception {
Map<String,Double> out=averages(List.of(new Employee("IT",100),new Employee("IT",80),new Employee("HR",60)));
System.out.println(new TreeMap<>(out));
if(out.get("IT")!=90.0 || out.get("HR")!=60.0)throw new AssertionError();
}
}
Complexity analysis

Time: O(n) expected grouping; sorted display O(g log g).

Auxiliary space: O(g)

Test cases
  • Empty input.
  • Single employee.
  • Repeated department.
Supplied main asserts IT=90.0 and HR=60.0; assert averages(List.of()).isEmpty().
Common mistakes
  • Using integer division.
  • Assuming groupingBy returns sorted keys.
Key takeaways
  • Separate accumulation from display.
  • Use a collector for per-group state.
  • Avoid side effects in streams.
Follow-up challenges
  • How would null departments be validated?
  • When would parallel streams be counterproductive?
Practise Java with the AI mentor

Can't find a Java topic you need for exams or placements? Request it and we'll add it.