猿问

Java 整数流

我是一个相当新的 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());




 }

 }


LEATH
浏览 128回答 1
1回答

牧羊人nacy

这就是你所需要的。Map<String, Double> avgSalByDept = Arrays.stream(employees).&nbsp; &nbsp; collect(Collectors.groupingBy(Employee::getDepartment,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Collectors.averagingDouble(Employee::getSalary)));首先使用groupingBy收集器Employees按部门分组。然后使用下游collector计算每个部门/组的平均工资。
随时随地看视频慕课网APP

相关分类

Java
我要回答