Introduction
Java 8 introduced the Stream API, which provides a powerful and expressive way to process collections of data. One common task in data processing is calculating the average value of a particular field within different groups. For instance, in an organization, you may want to calculate the average age of male and female employees separately. The Stream API, combined with Collectors.groupingBy and Collectors.averagingInt, makes this operation straightforward and efficient.
In this guide, we will explore how to use Java 8 streams to calculate and print the average age of male and female employees.
Table of Contents
- Problem Statement
- Solution Steps
- Java Program
- Example: Calculating and Printing the Average Age of Male and Female Employees
- Conclusion
Problem Statement
You need to calculate the average age of male and female employees from a list of Employee objects. This operation is common in scenarios where you need to analyze data based on specific groupings, such as gender.
Example:
- Problem: Given a list of
Employeeobjects, calculate and print the average age of male and female employees. - Goal: Use Java 8’s Stream API to efficiently calculate and print the average age by gender.
Solution Steps
- Create an Employee Class: Define an
Employeeclass with fields such as name, age, gender, and department. - Group Employees by Gender: Use
Collectors.groupingByto group employees by gender. - Calculate Average Age: Use
Collectors.averagingIntto calculate the average age for each gender group. - Print the Results: Display the average age for male and female employees.
Java Program
Example: Calculating and Printing the Average Age of Male and Female Employees
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 - Print Average Age of Male and Female Employees
* Author: https://www.rameshfadatare.com/
*/
public class AverageAgeByGenderExample {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Amit", 30, "Male", "IT"),
new Employee("Priya", 25, "Female", "HR"),
new Employee("Raj", 28, "Male", "Finance"),
new Employee("Suman", 24, "Female", "IT"),
new Employee("Kiran", 35, "Male", "HR")
);
// Group employees by gender and calculate the average age
Map<String, Double> averageAgeByGender = employees.stream()
.collect(Collectors.groupingBy(Employee::getGender, Collectors.averagingInt(Employee::getAge)));
// Print the average age by gender
averageAgeByGender.forEach((gender, avgAge) ->
System.out.println("Average age of " + gender + " employees: " + avgAge));
}
}
class Employee {
private String name;
private int age;
private String gender;
private String department;
public Employee(String name, int age, String gender, String department) {
this.name = name;
this.age = age;
this.gender = gender;
this.department = department;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
public String getDepartment() {
return department;
}
}
Output
Average age of Male employees: 31.0
Average age of Female employees: 24.5
Explanation
EmployeeClass: TheEmployeeclass includes fieldsname,age,gender, anddepartment. ThegetGender()andgetAge()methods are used to retrieve the gender and age of the employee.groupingBy(Employee::getGender, Collectors.averagingInt(Employee::getAge)): The Stream API groups employees by gender and calculates the average age for each gender group usingCollectors.averagingInt.forEach(): The average age for each gender is printed to the console.
Conclusion
Using Java 8’s Stream API, calculating and printing the average age of male and female employees is both efficient and straightforward. The combination of groupingBy and averagingInt collectors 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 salary or years of experience, based on different groupings, making the Stream API used for data analysis in Java.