Quantcast
Channel: Java 8 Examples
Viewing all articles
Browse latest Browse all 5

Calculating Sum, Avg, Min and Max of a List ( summaryStatistics ) in one command with Java 8 Streams

$
0
0

In Java 8 it is really easy to calculate the Sum, Average, Minimum and Maximum of a list on integers in one single line. There is this newly added class called: IntSummaryStatistics which has the following structure:

public class IntSummaryStatistics implements IntConsumer {
    private long count;
    private long sum;
    private int min = Integer.MAX_VALUE;
    private int max = Integer.MIN_VALUE;
    // see Java Docs for the methods
}

Let’s see how to use this in action. Suppose you have a list of integers as follows:

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);

Let’s convert this list to a Stream and use mapToInt to achieve this. If you are not familiar with mapToInt, it functions like a normal map however it is an specialization for int. Using it make your code more efficient while dealing with integers(boxing and unboxing per se). The actual name for it is “Numeric Stream” and it is available for int,long and double. Let’s see it in action:

final IntSummaryStatistics intSummaryStatistics = list.stream().mapToInt(Integer::intValue).summaryStatistics();
        System.out.println("intSummaryStatistics = " + intSummaryStatistics);

output is:

intSummaryStatistics = IntSummaryStatistics{count=7, sum=28, min=1, average=4.000000, max=7}

Cool huh?!

The post Calculating Sum, Avg, Min and Max of a List ( summaryStatistics ) in one command with Java 8 Streams appeared first on Java 8 Examples.


Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images