我是一个相当新的 Java 程序员,我目前正在学习流。我正在尝试使用流来获取每个部门的工资并对其进行平均。我已经能够添加工资或平均工资,但我无法弄清楚我将如何按部门执行此操作。这是我到目前为止的代码。
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class AverageSalariesDept {
public static void main(String[] args) {
Employee[] employees = {
new Employee("Jason", "Red", 5000, "IT"),
new Employee("Ashley", "Green", 7600, "IT"),
new Employee("Matthew", "Indigo", 3587.5, "Sales"),
new Employee("James", "Indigo", 4700.77, "Marketing"),
new Employee("Luke", "Indigo", 6200, "IT"),
new Employee("Jason", "Blue", 3200, "Sales"),
new Employee("Wendy", "Brown", 4236.4, "Marketing")};
List<Employee> list = Arrays.asList(employees);
Function<Employee, String> byDepartment = Employee::getDepartment;
Function<Employee, Double> bySalary = Employee::getSalary;
Comparator<Employee> compSalaries =
Comparator.comparing(byDepartment).thenComparing(bySalary);
list.stream()
.sorted(compSalaries)
.forEach(System.out::println);
System.out.printf("Average of Employees' salaries: %.2f%n",
list.stream()
.mapToDouble(Employee::getSalary)
.average()
.getAsDouble());
}
}
牧羊人nacy
相关分类