Introduction
Java 8 introduced the Stream API, which offers a powerful and functional way to process collections of data. A common task in data analysis is to calculate the average value of a certain field, such as the average salary in different departments within an organization. The Stream API, combined 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
You need to calculate the average salary of employees in each department from a list of Employee objects. This operation is useful in scenarios where you need to analyze salary distributions across different departments.
Example:
- Problem: Given a list of
Employeeobjects, calculate and print the average salary for each department. - Goal: Use Java 8’s Stream API to efficiently calculate and print the average salary by department.
Solution Steps
- Create an Employee Class: Define an
Employeeclass with fields such as name, department, and salary. - Group Employees by Department: Use
Collectors.groupingByto group employees by department. - Calculate the Average Salary: Use
Collectors.averagingDoubleto calculate the average salary for each department. - Print the Results: Display the average salary for each department.
Java Program
Example: Calculating and Printing the Average Salary of Each Department
First, define the Employee class with the necessary 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
EmployeeClass: TheEmployeeclass includes fieldsname,department, andsalary. ThegetDepartment()andgetSalary()methods are used to retrieve the department and salary of each employee.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)): The Stream API groups employees by department and calculates the average salary for each department usingCollectors.averagingDouble.forEach(): The average salary for each department is printed to the console.
Conclusion
Using Java 8’s Stream API, calculating and printing the average salary of each department is both efficient and straightforward. The combination of groupingBy and averagingDouble allows you to group data by specific attributes and calculate averages in a concise manner. This approach can be adapted to calculate other statistics, such as average experience or performance ratings, based on different groupings, making the Stream API used for data analysis in Java.