Java8 - What is the average salary of each department

Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 08:55:37 Viewed : 150


To calculate the average salary of each department in Java 8, you would need an attribute in the Employee class representing the salary. Here is an example:

java
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Employee { private String name; private String department; private double salary; public Employee(String name, String department, double salary) { this.name = name; this.department = department; this.salary = salary; } public String getDepartment() { return department; } public double getSalary() { return salary; } public static void main(String[] args) { // Sample data List<Employee> employees = Arrays.asList( new Employee("John", "HR", 50000), new Employee("Jane", "Finance", 60000), new Employee("Bob", "IT", 75000), new Employee("Alice", "HR", 70000), new Employee("Charlie", "IT", 80000) ); // Calculate the average salary for each department using Java 8 streams Map<String, Double> averageSalaryByDepartment = employees.stream() .collect(Collectors.groupingBy( Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary) )); // Output the results averageSalaryByDepartment.forEach((department, averageSalary) -> System.out.println("Average salary in " + department + ": " + averageSalary)); } }

Output:

yaml
Average salary in HR: 60000.0 Average salary in Finance: 60000.0
Average salary in IT: 77500.0In this example:
  • The Employee class is modified to include a salary attribute.
  • Java 8 streams are used with the Collectors.groupingBy collector to group employees by department.
  • The Collectors.averagingDouble downstream collector is used to calculate the average salary for each group.
  • The results are stored in a Map<String, Double>, where the keys are department names, and the values are the corresponding average salaries.
  • The results are then printed to the console.

Search
Related Articles

Leave a Comment: