Streams: Collectors.summingInt sums without a separate mapToInt call

summingInt takes a key extractor directly, folding the map-then-sum pattern into a single collector, and it composes with groupingBy for a per-group total.

Code
record Item(String name, int qty) {}
List<Item> items = List.of(new Item("bolt", 4), new Item("nut", 6), new Item("bolt", 2));
int total = items.stream().collect(Collectors.summingInt(Item::qty));
System.out.println("Total quantity: " + total);
Map<String, Integer> byName = items.stream()
        .collect(Collectors.groupingBy(Item::name, Collectors.summingInt(Item::qty)));
System.out.println("By name: " + new TreeMap<>(byName));
Output
Total quantity: 12
By name: {bolt=6, nut=6}
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms