MST

星途 面试题库

面试题:Java Stream collect方法实现复杂分组统计

给定一个包含员工信息的List<Employee>,Employee类有name(姓名)、department(部门)、salary(薪资)属性。要求使用Stream的collect方法,按部门分组统计每个部门的员工人数、平均薪资以及最高薪资,写出实现代码。
23.0万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
import java.util.*;
import java.util.stream.Collectors;

class Employee {
    private String name;
    private String department;
    private double salary;

    public Employee(String name, String department, double salary) {
        this.name = name;
        this.department = department;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public String getDepartment() {
        return department;
    }

    public double getSalary() {
        return salary;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
                new Employee("Alice", "HR", 5000.0),
                new Employee("Bob", "IT", 6000.0),
                new Employee("Charlie", "HR", 5500.0),
                new Employee("David", "IT", 7000.0)
        );

        Map<String, Map<String, Object>> result = employees.stream()
               .collect(Collectors.groupingBy(
                        Employee::getDepartment,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> {
                                    long count = list.size();
                                    double averageSalary = list.stream().mapToDouble(Employee::getSalary).average().orElse(0.0);
                                    double maxSalary = list.stream().mapToDouble(Employee::getSalary).max().orElse(0.0);
                                    return Map.of(
                                            "员工人数", count,
                                            "平均薪资", averageSalary,
                                            "最高薪资", maxSalary
                                    );
                                }
                        )
                ));

        result.forEach((department, stats) -> {
            System.out.println("部门: " + department);
            stats.forEach((key, value) -> {
                System.out.println(key + ": " + value);
            });
            System.out.println();
        });
    }
}

上述代码中:

  1. 定义了Employee类,包含namedepartmentsalary属性。
  2. main方法中创建了一个employees列表。
  3. 使用Streamcollect方法,结合Collectors.groupingByCollectors.collectingAndThen对员工按部门分组,并统计每个部门的员工人数、平均薪资和最高薪资。
  4. 最后遍历打印统计结果。