Java 8 – Find the Average Salary of Each Department

Introduction

In Java 8, the Stream API provides used for processing collections of data in a functional style. One common requirement in data analysis is calculating the average salary of employees within each department in an organization. The Stream API, in combination with Collectors.groupingBy and Collectors.averagingDouble, makes this calculation straightforward and efficient.

In this guide, we will explore how to use Java 8 streams to calculate and print the average salary of employees in each department.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Example: Calculating and Printing the Average Salary of Each Department
  • Conclusion

Problem Statement

Given a list of Employee objects, each containing information about the employee’s name, department, and salary, you need to calculate the average salary for each department.

Example:

  • Problem: Calculate the average salary of employees for each department.
  • Goal: Use Java 8’s Stream API to efficiently compute and display the average salary for each department.

Solution Steps

  1. Create an Employee Class: Define an Employee class with fields such as name, department, and salary.
  2. Group Employees by Department: Use Collectors.groupingBy to group employees by department.
  3. Calculate the Average Salary: Use Collectors.averagingDouble to compute the average salary for each department.
  4. Print the Results: Display the computed average salary for each department.

Java Program

Example: Calculating and Printing the Average Salary of Each Department

First, define the Employee class with the required fields.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Java 8 - Find the Average Salary of Each Department
 * Author: https://www.rameshfadatare.com/
 */
public class AverageSalaryByDepartmentExample {

    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Amit", "IT", 50000),
            new Employee("Priya", "HR", 60000),
            new Employee("Raj", "Finance", 70000),
            new Employee("Suman", "IT", 55000),
            new Employee("Kiran", "HR", 65000)
        );

        // Group employees by department and calculate the average salary
        Map<String, Double> averageSalaryByDepartment = employees.stream()
            .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)));

        // Print the average salary by department
        averageSalaryByDepartment.forEach((department, avgSalary) -> 
            System.out.println("Department: " + department + ", Average Salary: " + avgSalary));
    }
}

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 getName() {
        return name;
    }

    public String getDepartment() {
        return department;
    }

    public double getSalary() {
        return salary;
    }
}

Output

Department: IT, Average Salary: 52500.0
Department: HR, Average Salary: 62500.0
Department: Finance, Average Salary: 70000.0

Explanation

  • Employee Class: This class includes fields name, department, and salary. The methods getDepartment() and getSalary() are used to retrieve the department and salary of each employee.
  • groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)): The Stream API is used to group employees by department and calculate the average salary for each department using Collectors.averagingDouble.
  • forEach(): The results are printed to the console, showing the average salary for each department.

Conclusion

Using Java 8’s Stream API, you can efficiently calculate and print the average salary of each department within an organization. The combination of groupingBy and averagingDouble allows for concise and powerful data processing, making it easier to analyze and report on key metrics such as average salary distribution across departments. This approach can be extended to calculate other statistics or metrics across various groupings, demonstrating the versatility of the Stream API in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top