Java 8 : How to sum Integer values with streams ?

Below follows an example that show how to get the sum total of all attributes contained in a collection.

Example :

int sumResult = allTests.stream()
        .mapToInt( a -> a.getNote() )
        .sum();

You can combine this with filters, like as :

int sumResult = allTests.stream()
        .filter( a -> a.hasNote() )
        .mapToInt( a -> a.getNote() )
        .sum();

Leave a comment