2024 / 7 / 22
private void initTotalPrice(WjCreateOrderReq req) { BigDecimal totalFee = req.getVehicleGoodsInfoList().stream() .map(VehicleGoodsInfo::getGoodTotalPrice) .reduce(BigDecimal.ZERO, BigDecimal::add); Optional<InsuranceGoodsInfo> insuranceGoodsInfo = Optional.ofNullable(req.getInsuranceGoodsInfo()); if (insuranceGoodsInfo.isPresent()) { totalFee = totalFee.add(insuranceGoodsInfo.get().getGoodTotalPrice()); } req.setOrderTotalFee(totalFee); }
使用 Stream API 简化 initTotalPrice 方法:
使用单行 Stream 操作合并 Optional 判断,使代码更简洁。
private void initTotalPrice(WjCreateOrderReq req) { req.setOrderTotalFee( req.getVehicleGoodsInfoList().stream() .map(VehicleGoodsInfo::getGoodTotalPrice) .reduce(BigDecimal.ZERO, BigDecimal::add) .add(Optional.ofNullable(req.getInsuranceGoodsInfo()) .map(InsuranceGoodsInfo::getGoodTotalPrice) .orElse(BigDecimal.ZERO)) ); }