How to create IntSummaryStatistics from Collectors in Java?


Let us first create a List:

List<Employee> emp = Arrays.asList(
   new Employee("John", "Marketing", 5),
   new Employee("David", "Operations", 10));

We have class Employee with name, department and rank of employees.

Now, create summary for the rank like count, average, sum, etc:

IntSummaryStatistics summary = emp .stream() .collect(Collectors.summarizingInt(p -> p.rank));

The following is an example to create IntSummaryStatistics from Collectors in Java:

Example

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;
public class Demo {
   public static void main(String[] args) throws Exception {
      List<Employee> emp = Arrays.asList(new Employee("John", "Marketing", 5), new Employee("David", "Operations", 10));
      IntSummaryStatistics summary = emp .stream() .collect(Collectors.summarizingInt(p → p.rank));
      System.out.println("Summary Statistics = "+summary);
   }
}
class Employee {
   String name;
   String department;
   int rank;
   Employee(String name, String department, int rank) {
      this.name = name;
      this.department = department;
      this.rank = rank;
   }
}

Output

Summary Statistics = IntSummaryStatistics{count=2, sum=15, min=5, average=7.500000, max=10}

Updated on: 30-Jul-2019

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements