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
5Notes
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
- IntStream.average() — Computes the arithmetic mean of the numbers in a stream.
- Stream.mapToInt() — Turns a stream of objects into a stream of `int` numbers.
- Stream.reduce() — Folds all stream elements into a single value.
- Collectors.summingInt() — A collector that sums a numeric field of the elements.
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.