LongSummaryStatistics in Java8

Java Streams are a powerful tool to get rid of boilerplate code. One has never computed the min, max, average and count on a list of longs?

Here’s a way to do it with LongSummaryStatistics

LongSummaryStatistics stats = persons.stream().mapToLong(Person::getAge).summaryStatistics();

System.out.println(stats.getCount());
System.out.println(stats.getAverage());
System.out.println(stats.getMin());
System.out.println(stats.getMax());

2 thoughts on “LongSummaryStatistics in Java8”

    1. summaryStatistics() is a terminal operation. That means it consumes the elements in the stream to actually compute the statistics.

Comments are closed.