Generate Summary Statistics of a List in Java 8

Problem:

Using Java 8 Streams, how do you quickly find minimum, maximum, sum, average, and count of numbers in a list without writing separate loops?

✅ Example:

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;

public class SummaryStatisticsExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(5, 3, 9, 1, 7);

        // Generate summary statistics
        IntSummaryStatistics stats = numbers.stream()
            .mapToInt(n -> n)  // Convert Integer to int
            .summaryStatistics();

        // Print results
        System.out.println("Minimum: " + stats.getMin());
        System.out.println("Maximum: " + stats.getMax());
        System.out.println("Sum: " + stats.getSum());
        System.out.println("Average: " + stats.getAverage());
        System.out.println("Count: " + stats.getCount());
    }
}

✅ Explanation:

  1. numbers.stream(): Create a stream of integers from the list.
  2. mapToInt(n -> n): Converts the Stream<Integer> into an IntStream. This is necessary because IntSummaryStatistics works with primitive int.
  3. summaryStatistics(): This terminal operation generates an IntSummaryStatistics object, which contains:
    • Minimum value → getMin()
    • Maximum value → getMax()
    • Sum of all numbers → getSum()
    • Average → getAverage()
    • Count of elements → getCount()
  4. The results are printed using System.out.println.

✅ Output:

Minimum: 1
Maximum: 9
Sum: 25
Average: 5.0
Count: 5

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *