<p>直接用 mapToInt(Item::getPrice).sum() 一行计算总价,要求 getPrice() 返回 int/Integer;若为 double/BigDecimal 需先转换;空流 sum() 返回 0,但需防 null 用 filter 或三元判断;加权求和则 mapToInt(item -> item.getPrice() * item.getQuantity())。</p>

直接用 mapToInt 把商品单价映射为 int 流,再调用 sum() 就能一步算出总价,比手动循环简洁又高效。
确保商品对象有可提取的 int 类型价格字段
比如商品类 Item 有个 getPrice() 方法,返回 int(或自动拆箱的 Integer):
- 如果价格是
int或Integer,mapToInt(Item::getPrice)可直接使用 - 如果价格是
double或BigDecimal,不能直接用mapToInt,需先转成整数(如乘以 100 存为分),或改用mapToDouble+sum()
一行代码完成求和
假设 cart 是 List<item></item>,写法如下:
int total = cart.stream().mapToInt(Item::getPrice).sum();
-
stream()创建流 -
mapToInt(...)转成IntStream,避免装箱开销 -
sum()是IntStream的终端操作,直接返回int总和
注意空集合和 null 安全
sum() 对空流返回 0,无需额外判空;但若 Item 或 getPrice() 可能为 null,要提前过滤:
立即学习“Java免费学习笔记(深入)”;
- 加
.filter(Objects::nonNull)防止NullPointerException - 或在
mapToInt前用.mapToInt(item -> item.getPrice() != null ? item.getPrice() : 0)
扩展:需要按数量加权计算时
如果每个商品还有 quantity 字段,不能只 map 价格,得先算单个商品金额:
- 用
mapToInt(item -> item.getPrice() * item.getQuantity()) - 再调
.sum(),依然保持一次流式处理


















