LearnFrenzy
Sign in Take a free test

Streams API · Streams API Programs · Question 3

Department salary report with collectors in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

For each department print the head count, total and average salary and the highest-paid employee, using a single groupingBy into a TreeMap and a summary record.

Solution
Main.java
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

record Emp(String name, String dept, int salary) { }

public class Main {
    public static void main(String[] args) {
        List<Emp> staff = List.of(new Emp("Asha", "IT", 90000), new Emp("Ravi", "HR", 48000), new Emp("Meena", "IT", 105000),
                                  new Emp("John", "Sales", 62000), new Emp("Zoya", "HR", 51000), new Emp("Neha", "IT", 72000), new Emp("Amit", "Sales", 58000));

        Map<String, List<Emp>> byDept = staff.stream().collect(Collectors.groupingBy(Emp::dept, TreeMap::new, Collectors.toList()));
        byDept.forEach((dept, list) -> {
            int total = list.stream().mapToInt(Emp::salary).sum();
            String top = list.stream().max(Comparator.comparingInt(Emp::salary)).map(Emp::name).orElse("-");
            System.out.printf("%-6s %d staff  total %,8d  avg %,9.2f  top %s%n", dept, list.size(), total, (double) total / list.size(), top);
        });
        System.out.printf("company payroll %,d%n", staff.stream().mapToInt(Emp::salary).sum());
    }
}

Output Verified by compiling and running

HR     2 staff  total   99,000  avg 49,500.00  top Zoya
IT     3 staff  total  267,000  avg 89,000.00  top Meena
Sales  2 staff  total  120,000  avg 60,000.00  top John
company payroll 486,000

Grouping once into a TreeMap gives sorted departments; each group is then summarised with small streams.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links