2

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



 }
 }
0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.