You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用.map()/.filter()累加不同类中的费用变量至totalDeliveryFee

完善CartEntryTotalDeliveryFeeCalculator实现费用累加逻辑

先修正原代码里的拼写错误(Fullfillment → Fulfillment)和语法问题(方法参数括号缺失),再调整Optional的处理逻辑——原逻辑中只要任一对象/字段为null就直接终止计算,不符合累加需求,应该对null字段用0值兜底,最终实现三者的累加并赋值。

以下是完整的实现代码:

package core.calculator.cartEntry.impl;

import core.aggregate.CartEntry;
import core.aggregate.Fulfillment;
import core.aggregate.StoreDelivery;
import core.calculator.cartEntry.CartEntryCalculator;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.Optional;

public class CartEntryTotalDeliveryFeeCalculator implements CartEntryCalculator {
    @Override
    public void calculate(final CartEntry cartEntry) {
        // 从CartEntry开始逐层安全获取对象,对null字段用0兜底计算
        BigDecimal total = Optional.ofNullable(cartEntry)
                .map(CartEntry::getFulfillment)
                .map(Fulfillment::getStoreDelivery)
                .map(storeDelivery -> {
                    // 获取cost,null则用0
                    BigDecimal cost = Optional.ofNullable(storeDelivery.getCost())
                            .orElse(BigDecimal.ZERO);
                    // 获取deliveryServiceFee,null则用0
                    BigDecimal deliveryServiceFee = Optional.ofNullable(storeDelivery.getDeliveryServiceFee())
                            .orElse(BigDecimal.ZERO);
                    // 获取DeliveryWindow的fee,null则用0
                    BigDecimal windowFee = Optional.ofNullable(storeDelivery.getDeliveryWindow())
                            .map(DeliveryWindow::getFee)
                            .orElse(BigDecimal.ZERO);
                    // 三者累加
                    return cost.add(deliveryServiceFee).add(windowFee);
                })
                // 如果整个链路中任一上层对象为null,总费用设为0
                .orElse(BigDecimal.ZERO);
        
        // 将计算结果赋值给CartEntry的totalDeliveryFee
        if (Objects.nonNull(cartEntry)) {
            cartEntry.setTotalDeliveryFee(total);
        }
    }
}

关键说明:

  • 空值处理:所有可能为null的字段(cost、deliveryServiceFee、fee)以及上层对象(Fulfillment、StoreDelivery、DeliveryWindow)都通过Optional.ofNullable和orElse(BigDecimal.ZERO)做了兜底,既避免空指针异常,又保证即使部分费用不存在也能正常计算总和。
  • 累加逻辑:获取到StoreDelivery后,分别取出三个费用值(兜底后),通过BigDecimal.add()完成累加。
  • 结果赋值:最后将计算得到的总费用设置到CartEntry的totalDeliveryFee字段中,同时判断cartEntry本身是否为null,避免不必要的空指针。

内容的提问来源于stack exchange,提问作者Manu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:05:13