Java Int Streams

Michael Fogarty :

I am a fairly new Java programmer and I am currently learning about streams. I am trying to use a stream to take the salaries from each department and average them. I've been able to add the salaries or average them but I can't figure out how I would do this by department. Here's the code that I have so far.

 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());



 }
 }
Ravindra Ranwala :

This is what you need.

Map<String, Double> avgSalByDept = Arrays.stream(employees).
    collect(Collectors.groupingBy(Employee::getDepartment, 
        Collectors.averagingDouble(Employee::getSalary)));

First use the groupingBy collector to group Employees by department. Then use the downstream collector to compute the average salary for each department/group.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=91880&siteId=1