为了账号安全,请及时绑定邮箱和手机立即绑定

Java 整数流

Java 整数流

LEATH 2021-10-20 11:20:48
我是一个相当新的 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()); } }
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

这就是你所需要的。


Map<String, Double> avgSalByDept = Arrays.stream(employees).

    collect(Collectors.groupingBy(Employee::getDepartment, 

        Collectors.averagingDouble(Employee::getSalary)));

首先使用groupingBy收集器Employees按部门分组。然后使用下游collector计算每个部门/组的平均工资。


查看完整回答
反对 回复 2021-10-20
  • 1 回答
  • 0 关注
  • 127 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信