Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

IntStream.sum()

Adds up all numbers of a stream.

Available since: Java 8

Syntax

int sum()

Return value

intThe sum of the elements; `0` for an empty stream.

Examples

A sum of numbers and a sum of fields:

record Item(String name, int qty) {}
 
void main() {
    IO.println(IntStream.of(4, 8, 15).sum());
    var cart = List.of(new Item("tea", 2), new Item("milk", 3));
    IO.println(cart.stream().mapToInt(Item::qty).sum());
}

Output:

27
5

Notes

The method exists only on numeric streams (IntStream, LongStream, DoubleStream), so from a Stream<Integer> you first switch with mapToInt(). On int overflow the result wraps into negative values without an error — for large sums use mapToLong().

See also

Related recipes

In the tutorial

  • Stream operations — The main Stream API operations — filter, map, sorted, distinct, limit, skip, count, reduce, anyMatch, findFirst and numeric streams.

Thanks for reading!

Donate to the site — we work hard for you.