面试题答案
一键面试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();
});
}
}
上述代码中:
- 定义了
Employee
类,包含name
、department
和salary
属性。 - 在
main
方法中创建了一个employees
列表。 - 使用
Stream
的collect
方法,结合Collectors.groupingBy
和Collectors.collectingAndThen
对员工按部门分组,并统计每个部门的员工人数、平均薪资和最高薪资。 - 最后遍历打印统计结果。