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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s