Collectors.summingInt()
A collector that sums a numeric field of the elements.
Available since: Java 8
Syntax
static <T> Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper)Parameters
| Parameter | Type | Description |
|---|---|---|
| mapper | ToIntFunction<? super T> | Extracts the number to add from an element. |
Return value
Collector<T, ?, Integer>A sum collector.
Examples
Item quantities per warehouse:
record Stock(String warehouse, int qty) {}
void main() {
var stock = List.of(new Stock("north", 5), new Stock("south", 3), new Stock("north", 7));
Map<String, Integer> totals = stock.stream()
.collect(Collectors.groupingBy(Stock::warehouse, TreeMap::new, Collectors.summingInt(Stock::qty)));
IO.println(totals);
}Output:
{north=12, south=3}Notes
It is useful inside groupingBy(). For a simple total of the whole stream mapToInt(...).sum() is shorter. There are also summingLong() and summingDouble().
See also
- Collectors.groupingBy() — A collector that sorts elements into groups that share a key.
- IntStream.sum() — Adds up all numbers of a stream.
- Collectors.averagingDouble() — A collector that computes the mean of a numeric field.
Related recipes
In the tutorial
- Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.