Using summingInt with Method References
You'll learn how to combine summingInt with method references to elegantly extract and sum integer properties from objects in a single, readable operation.
The Power of Method References with summingInt
You already know summingInt(ToIntFunction) extracts integer values and sums them. When your objects have getter methods that return integers, method references provide the cleanest syntax possible—eliminating lambda clutter and making your intent crystal-clear.
Instead of writing:
Collectors.summingInt(product -> product.getQuantity())
You can use a method reference:
Collectors.summingInt(Product::getQuantity)
The method reference Product::getQuantity is a ToIntFunction<Product>—it takes a Product and returns an int. Java automatically converts it to the functional interface summingInt expects.
Real-World Example
Imagine calculating total inventory across warehouses:
class WarehouseItem {
private String name;
private int stock;
public WarehouseItem(String name, int stock) {
this.name = name;
this.stock = stock;
}
public int getStock() { return stock; }
}
List<WarehouseItem> inventory = List.of(
new WarehouseItem("Laptop", 150),
new WarehouseItem("Mouse", 300),
new WarehouseItem("Keyboard", 200)
);
int totalStock = inventory.stream()
.collect(Collectors.summingInt(WarehouseItem::getStock));
// totalStock = 650
The method reference WarehouseItem::getStock is concise, self-documenting, and type-safe. It's immediately obvious you're summing stock levels.
Why This Matters
Method references with summingInt transform what could be verbose into something elegant. They work perfectly with any getter returning int, making data aggregation code read almost like natural language.
Key Takeaway:
Use method references with summingInt to create clean, readable aggregations—summingInt(ClassName::getterMethod) is the idiomatic way to sum integer properties from objects.