Sum of salaries of employees using java streams, reduce and binaryoperator

We have been asked to find the sum of salaries of all the Employees.

We are provided with below schema of the Employee record. It contains, FirstName, LastName and Salary.

record Employee(String firstName, String secondName, double salary){}

We are going to use java stream to iterate over the employees, get their salaries and use BinaryOperator to calculate the sum.

// create a record to store employee informaion
record Employee ( String firstName, String secondName, double salary ) {}

// create a list of employees
final List<Employee> employees = List.of(new Employee("FName1", "LName1", 12.3), new Employee("FName2", "LName2", 32.3), new Employee("FName3", "LName3", 19.76));

// create a stream of Employee
final Stream<Employee> streamOfEmployees =;

// Create a steam of salary
final DoubleStream streamOfSalary = streamOfEmployees.mapToDouble(Employee::salary);

// Reduce the stream of double, by adding the salaries
final OptionalDouble optionalSalary = streamOfSalary.reduce((salary1, salary2) -> salary1 + salary2);

// Get the salary from the optional wrapper
final double totalSalary = optionalSum.getAsDouble();

In the above example, we had a list of employees , so we got OptionalDouble in the result. But in the case, where Employee List is empty, we will get Optional.empty.

We should look out of this edge-case, where data is not present. Otherwise will throw exceptions on calling get function.