答案:Collectors.summingInt用于对集合中对象的int属性求和,需配合Stream API使用,通过ToIntFunction提取值并累加。示例中统计Product列表的price总和为45,适用于List、Set等集合类型,仅支持int类型,null值需提前处理,性能良好,适合数据聚合。

在Java中,可以通过 Collectors.summingInt 方法对集合中的元素按指定整数属性进行求和。这个方法通常与 Stream API 配合使用,适用于统计对象列表中某个int类型字段的总和。
Collectors.summingInt 接收一个 ToIntFunction 函数式接口作为参数,用于提取每个元素的int值,然后将这些值累加返回总和。
假设有一个商品类 Product,包含名称和价格:
class Product {
private String name;
private int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
public int getPrice() {
return price;
}
}
现在有一个商品列表,想要统计所有商品的总价格:
立即学习“Java免费学习笔记(深入)”;
import <a style="color:#f60; text-decoration:underline;" title="java" href="https://www.php.cn/zt/15731.html" target="_blank">java</a>.util.*;
import java.util.<a style="color:#f60; text-decoration:underline;" title="stream" href="https://www.php.cn/zt/19633.html" target="_blank">stream</a>.Collectors;
List<Product> products = Arrays.asList(
new Product("Apple", 10),
new Product("Banana", 20),
new Product("Orange", 15)
);
int total = products.stream()
.collect(Collectors.summingInt(Product::getPrice));
System.out.println("总价格: " + total); // 输出:总价格: 45
<h3>适用场景和注意事项</h3>
以上就是Java中如何通过Collectors.summingInt统计总数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号