In this tutorial, I am going to show you how to calculate the total salaries of employees using Java 8 summingInt.

Java 8 summingInt :

summingInt(ToIntFunction<? super T> mapper) is method in Collector class. It produces the sum of an integer-valued function applied to the input elements.

Like summingInt(), summingLong(ToLongFunction<? super T> mapper) also a method in same Collector class. It produces the sum of a long-valued function applied to the input elements.

Here is the example to calculate the sum of salaries of employees.

Employee.java
class Employee {
 private int id;
 private int deptId;
 private String name;
 private int salary;

 public Employee(int id, int deptId, String name, int salary) {
  super();
  this.id = id;
  this.deptId = deptId;
  this.name = name;
  this.salary = salary;
 }
 public int getId() {
  return id;
 }
 public String getName() {
  return name;
 }
 public int getSalary() {
  return salary;
 }
 public int getDeptId() {
  return deptId;
 }

}

Calculating the summingInt on Employees salary.

Java8_SummingInt.java
package com.onlinetutorialspoint.java8;

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

public class Java8_SummingInt {
 public static void main(String[] args) {
  List < Employee > employees = Arrays.asList(new Employee(1, 1000,
    "Chandra Shekhar", 6000),
   new Employee(1, 1000, "Rajesh", 8000), new Employee(1, 1004,
    "Rahul", 9000), new Employee(1, 1001, "Suresh", 12000),
   new Employee(1, 1004, "Satosh", 8500));

  int total = employees.stream().collect(
   Collectors.summingInt(Employee::getSalary));
  System.out.println("Total Employees Salary : " + total);
 }

}

Output:

Total Employees Salary : 43500

Calculate the Sum by Dept :

We can also calculate the sum of salaries by filtering the department ids by using Stream filters in Java 8.

Java8_SummingInt.java
package com.onlinetutorialspoint.java8;

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

public class Java8_SummingInt {
 public static void main(String[] args) {
  List < Employee > employees = Arrays.asList(new Employee(1, 1000, "Chandra Shekhar", 6000),
   new Employee(1, 1000, "Rajesh", 8000),
   new Employee(1, 1004, "Rahul", 9000),
   new Employee(1, 1001, "Suresh", 12000),
   new Employee(1, 1004, "Satosh", 8500)
  );

  int total = employees.stream()
   .collect(Collectors.summingInt(Employee::getSalary));

  int totalSalByDept = employees.stream().
  filter(name -> 1000 == name.getDeptId())
   .collect(Collectors.summingInt(Employee::getSalary));

  System.out.println("Total Employees Salary : " + total);
  System.out.println("Total Employees Salary of 1000 Dept : " + totalSalByDept);
 }

}

Output:

Total Employees Salary : 43500
Total Employees Salary of 1000 Dept : 14000

Happy Learning 🙂