Introduction
Java 8 introduced the Stream API, which provides a powerful and concise way to process collections of data. A common requirement in data analysis is to calculate the total and average salary of all employees in an organization. The Stream API, along with the Collectors utility, makes these calculations straightforward and efficient.
In this guide, we will explore how to use Java 8 streams to calculate and print both the total and average salary of employees in an organization.
Table of Contents
- Problem Statement
- Solution Steps
- Java Program
- Example: Calculating and Printing the Total and Average Salary of the Organization
- Conclusion
Problem Statement
Given a list of Employee objects, each containing information about the employee’s name and salary, you need to calculate the total and average salary of all employees in the organization.
Example:
- Problem: Calculate the total and average salary of all employees in the organization.
- Goal: Use Java 8’s Stream API to efficiently compute and display both the total and average salary.
Solution Steps
- Create an Employee Class: Define an
Employeeclass with fields such as name and salary. - Calculate the Total Salary: Use
mapToDoubleandsummethods to calculate the total salary. - Calculate the Average Salary: Use
Collectors.averagingDoubleto calculate the average salary. - Print the Results: Display the total and average salary of the organization.
Java Program
Example: Calculating and Printing the Total and Average Salary of the Organization
First, define the Employee class with the required fields.
import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;
/**
* Java 8 - Print Average and Total Salary of the Organization
* Author: https://www.rameshfadatare.com/
*/
public class TotalAndAverageSalaryExample {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Amit", 50000),
new Employee("Priya", 60000),
new Employee("Raj", 70000),
new Employee("Suman", 55000),
new Employee("Kiran", 65000)
);
// Calculate the total salary of the organization
double totalSalary = employees.stream()
.mapToDouble(Employee::getSalary)
.sum();
// Calculate the average salary of the organization
OptionalDouble averageSalary = employees.stream()
.mapToDouble(Employee::getSalary)
.average();
// Print the total and average salary
System.out.println("Total Salary of the Organization: " + totalSalary);
System.out.println("Average Salary of the Organization: " +
(averageSalary.isPresent() ? averageSalary.getAsDouble() : "N/A"));
}
}
class Employee {
private String name;
private double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
Output
Total Salary of the Organization: 300000.0
Average Salary of the Organization: 60000.0
Explanation
EmployeeClass: This class includes fieldsnameandsalary. ThegetSalary()method is used to retrieve the salary of each employee.mapToDouble(Employee::getSalary): This method maps eachEmployeeobject to itssalaryvalue as adouble.sum(): This method calculates the total salary by summing all the salary values.average(): This method calculates the average salary. The result is anOptionalDoubleto handle cases where the stream might be empty.getAsDouble(): This method retrieves the value from theOptionalDouble. If the stream was empty, a default message is printed instead.
Conclusion
Using Java 8’s Stream API, calculating and printing both the total and average salary of an organization is efficient and straightforward. The combination of mapToDouble, sum, and average methods allows for concise and powerful data processing. This approach can be extended to other aggregate functions, making the Stream API used for data analysis tasks in Java.