Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
mapperToIntFunction<? 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

Related recipes

In the tutorial

  • Grouping — Grouping stream elements in Java — Collectors.groupingBy, counts and sums per group, mapping, TreeMap and partitioningBy.

Thanks for reading!

Donate to the site — we work hard for you.