Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 08:55:37 Viewed : 835
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:
javaimport 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:
yamlAverage salary in HR: 60000.0
Average salary in Finance: 60000.0
Average salary in IT: 77500.0In this example:
Employee
class is modified to include a salary
attribute.Collectors.groupingBy
collector to group employees by department.Collectors.averagingDouble
downstream collector is used to calculate the average salary for each group.Map<String, Double>
, where the keys are department names, and the values are the corresponding average salaries.