Simple salary computations using Java 8 Lambda Expressions (Collectors.groupingBy)

Simple salary computations using Java 8 Lambda Expressions (Collectors.groupingBy)

Collectors.groupingBy is a built-in Java 8 Collector provided by the Collectors class, used for categorizing elements during streaming operation. It accepts two arguments—a function mapping each element to be categorized into a specific group, referred to as the classification function, and a downstream Collector handling the accumulation process within each category.


First, let us define our Employee class, which contains three properties: name, department, and salary. We also provide getter methods for these fields.

class Employee {
    // ... (other class definitions)

    public String getDepartment() {
        return department;
    }

    public double getSalary() {
        return salary;
    }
}        

Next, we create the SalaryCalculator utility class that houses the method responsible for computing the total salary by department. The key challenge here is aggregating the individual employee salaries grouped by their respective departments. To achieve this, we utilize Java 8's Stream and Collector classes as follows:

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

public class SalaryCalculator {

    /**
     * Calculates the total salary for each department given a list of employees.
     *
     * @param employees A list of Employee objects representing the input dataset.
     * @return A Map where the keys are department names, and the values are the corresponding total salaries.
     */
    public static Map<String, Double> calculateTotalSalaryByDepartment(List<Employee> employees) {
        return employees.stream()
            .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.summingDouble(Employee::getSalary)
            ));
    }
}        

The calculateTotalSalaryByDepartment method takes advantage of two collector operations provided by the Collectors class: groupingBy and summingDouble.

Initially, it groups employees according to their departments using the groupingBy collector. Next, within each group, it computes the sum of the salaries using the summingDouble collector. As a result, the final output is a map containing department names as keys and corresponding total salaries as values.

Lastly, let us initialize sample usage scenario in the main method. We will instantiate several Employee objects belonging to different departments along with varying salaries. Then, we invoke the calculateTotalSalaryByDepartment method, passing in the employee roster as its argument, followed by printing the computed results.

public static void main(String[] args) {
    List<Employee> employees = Arrays.asList(
        new Employee("John Doe", "IT", 5000.0),
        new Employee("Jane Smith", "HR", 4500.0),
        new Employee("Bob Johnson", "IT", 6000.0),
        new Employee("Alice Williams", "HR", 5200.0),
        new Employee("Charlie Brown", "Finance", 6500.0)
    );

    Map<String, Double> totalSalaryByDepartment = calculateTotalSalaryByDepartment(employees);
    System.out.println(totalSalaryByDepartment);
}        

This example illustrates how leveraging Java 8 lambda expressions can significantly reduce boilerplate code. I also enhances readability and maintainability when dealing with intricate object hierarchies.

Full Code:

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

public class SalaryCalculator {

    /**
     * Calculates the total salary for each department given a list of employees.
     *
     * @param employees A list of Employee objects representing the input dataset.
     * @return A Map where the keys are department names, and the values are the corresponding total salaries.
     */
    public static Map<String, Double> calculateTotalSalaryByDepartment(List<Employee> employees) {
        return employees.stream()
                .collect(Collectors.groupingBy(
                        Employee::getDepartment,
                        Collectors.summingDouble(Employee::getSalary)
                ));
    }

    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
                new Employee("John Doe", "IT", 5000.0),
                new Employee("Jane Smith", "HR", 4500.0),
                new Employee("Bob Johnson", "IT", 6000.0),
                new Employee("Alice Williams", "HR", 5200.0),
                new Employee("Charlie Brown", "Finance", 6500.0)
        );

        Map<String, Double> totalSalaryByDepartment = calculateTotalSalaryByDepartment(employees);
        System.out.println(totalSalaryByDepartment);
    }
}

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;
    }
}
        

Thank you and see you on the next tutorial!


To view or add a comment, sign in

More articles by Arjun Araneta

Explore content categories