Java Stream How to - Create IntSummaryStatistics from Collectors








Question

We would like to know how to create IntSummaryStatistics from Collectors.

Answer

/*w w  w. j av  a  2s  .co m*/
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

  public static void main(String[] args) throws Exception {
    List<Person> persons =
        Arrays.asList(
            new Person("Max", 18),
            new Person("Peter", 23),
            new Person("Pamela", 23),
            new Person("David", 12));   
    

    IntSummaryStatistics ageSummary =
        persons
            .stream()
            .collect(Collectors.summarizingInt(p -> p.age));

    System.out.println(ageSummary);
  }

}
class Person {
  String name;
  int age;

  Person(String name, int age) {
      this.name = name;
      this.age = age;
  }

  @Override
  public String toString() {
      return name;
  }
}

The code above generates the following result.