当前位置: 首页 > 图灵资讯 > 技术篇> Java Stream API处理嵌套对象字段求和:以购物车条目为例

Java Stream API处理嵌套对象字段求和:以购物车条目为例

来源:图灵教育
时间:2025-09-08 17:17:41

Java Stream API处理嵌套对象字段求和:以购物车条目为例

本文探讨了如何使用Java Stream API有效地聚合了复杂嵌套对象中的数值字段。通过购物车条目的具体案例,演示了如何从多层次对象中提取和累积BigDecimal类型的成本数据,强调了MaptoDouble、BigDecimal的精确计算以及在处理可能为空的字段时,结合注释判断null值的关键注意事项。

在现代java应用程序开发中,数据模型通常涉及多层嵌套对象结构。当我们需要从这些深层结构中提取特定的值并进行聚合计算时,如何有效和优雅地实现它是一个常见的挑战。本教程将以典型的电子商务购物车场景为例,展示如何使用java stream 解决这个问题的api。

问题场景:嵌套成本数据聚合

假设我们有以下一系列Java类,它们共同构成了购物车的一个项目及其相关费用信息:

  • CartEntry:购物车条目,包括Fulfillment对象,并计划存储totaldeliveryfeee。
  • Fulfillment:包含Storedelivery对象的配送信息。
  • StoreDelivery:店铺配送细节包括cost(成本)、deliveryservicefee(配送服务费)和deliverywindow对象。
  • DeliveryWindow:配送窗口,包括一个fee(窗口费)。

我们的目标是从CartEntry列表中嵌入每个CartEntry中的costry列表。、deliveryservicefeee和fee这三种bigdecimal类型的字段值积累在一起,形成总的配送成本。

传统的迭代和Streamm API对比

如果采用传统的循环迭代方法,我们需要编写多层嵌套if判断和for循环,逐层访问对象并积累,代码将显得冗长且容易出错。Java Streamm引入Stream API为这一场景提供了更简洁、更有表现力的解决方案。

采用Stream 高效的API和

解决这个问题的核心是使用Stream 结合BigDecimal的精确计算能力,APImaptodouble操作。以下是实现这一目标的推荐方法:

立即学习“Java免费学习笔记(深入);

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

// 假设类结构,与问题描述一致
class CartEntry {
    private Fulfillment fulfillment;
    private BigDecimal totalDeliveryFee = BigDecimal.ZERO; // 初始化为0

    public CartEntry(Fulfillment fulfillment) {
        this.fulfillment = fulfillment;
    }

    public Fulfillment getFulfillment() {
        return fulfillment;
    }

    public BigDecimal getTotalDeliveryFee() {
        return totalDeliveryFee;
    }

    public void setTotalDeliveryFee(BigDecimal totalDeliveryFee) {
        this.totalDeliveryFee = totalDeliveryFee;
    }
}

class Fulfillment {
    private StoreDelivery storeDelivery;

    public Fulfillment(StoreDelivery storeDelivery) {
        this.storeDelivery = storeDelivery;
    }

    public StoreDelivery getStoreDelivery() {
        return storeDelivery;
    }
}

class StoreDelivery {
    private BigDecimal cost = BigDecimal.ZERO;
    private BigDecimal deliveryServiceFee = BigDecimal.ZERO;
    private DeliveryWindow deliveryWindow;

    public StoreDelivery(BigDecimal cost, BigDecimal deliveryServiceFee, DeliveryWindow deliveryWindow) {
        this.cost = cost;
        this.deliveryServiceFee = deliveryServiceFee;
        this.deliveryWindow = deliveryWindow;
    }

    public BigDecimal getCost() {
        return cost;
    }

    public BigDecimal getDeliveryServiceFee() {
        return deliveryServiceFee;
    }

    public DeliveryWindow getDeliveryWindow() {
        return deliveryWindow;
    }
}

class DeliveryWindow {
    private BigDecimal fee = BigDecimal.ZERO;

    public DeliveryWindow(BigDecimal fee) {
        this.fee = fee;
    }

    public BigDecimal getFee() {
        return fee;
    }
}

public class CartEntryTotalDeliveryFeeCalculator {

    public static double calculateTotalDeliveryFee(List<CartEntry> entries) {
        if (entries == null || entries.isEmpty()) {
            return 0.0;
        }

        return entries.stream()
            .mapToDouble(entry -> {
                // 当前条目总费用的初始化
                BigDecimal currentEntryTotal = BigDecimal.ZERO;

                // 试着获得Cartentry自己的totaldeliveryFeee(如果有值)
                currentEntryTotal = currentEntryTotal.add(
                    Optional.ofNullable(entry.getTotalDeliveryFee()).orElse(BigDecimal.ZERO)
                );

                // 试着获得Fulfillment -> StoreDelivery -> cost
                currentEntryTotal = currentEntryTotal.add(
                    Optional.ofNullable(entry.getFulfillment())
                        .map(Fulfillment::getStoreDelivery)
                        .map(StoreDelivery::getCost)
                        .orElse(BigDecimal.ZERO)
                );

                // 试着获得Fulfillment -> StoreDelivery -> deliveryServiceFee
                currentEntryTotal = currentEntryTotal.add(
                    Optional.ofNullable(entry.getFulfillment())
                        .map(Fulfillment::getStoreDelivery)
                        .map(StoreDelivery::getDeliveryServiceFee)
                        .orElse(BigDecimal.ZERO)
                );

                // 试着获得Fulfillment -> StoreDelivery -> DeliveryWindow -> fee
                currentEntryTotal = currentEntryTotal.add(
                    Optional.ofNullable(entry.getFulfillment())
                        .map(Fulfillment::getStoreDelivery)
                        .map(StoreDelivery::getDeliveryWindow)
                        .map(DeliveryWindow::getFee)
                        .orElse(BigDecimal.ZERO)
                );

                return currentEntryTotal.doubleValue();
            })
            .sum();
    }

    public static void main(String[] args) {
        // 示例数据
        DeliveryWindow dw1 = new DeliveryWindow(new BigDecimal("5.00"));
        StoreDelivery sd1 = new StoreDelivery(new BigDecimal("10.50"), new BigDecimal("2.25"), dw1);
        Fulfillment f1 = new Fulfillment(sd1);
        CartEntry ce1 = new CartEntry(f1);
        ce1.setTotalDeliveryFee(new BigDecimal("1.00")); // 假设Cartentry本身也可能有初始费用

        DeliveryWindow dw2 = new DeliveryWindow(new BigDecimal("3.00"));
        StoreDelivery sd2 = new StoreDelivery(new BigDecimal("7.00"), new BigDecimal("1.50"), dw2);
        Fulfillment f2 = new Fulfillment(sd2);
        CartEntry ce2 = new CartEntry(f2);

        // 场景包含null值
        CartEntry ce3 = new CartEntry(null); // Fulfillment
        CartEntry ce4 = new CartEntry(new Fulfillment(null)); // 没有Storedelivery
        CartEntry ce5 = new CartEntry(new Fulfillment(new StoreDelivery(new BigDecimal("2.00"), null, null))); // 有些字段是null

        List<CartEntry> entries = List.of(ce1, ce2, ce3, ce4, ce5);

        double total = calculateTotalDeliveryFee(entries);
        System.out.println("所有购物车项目的总配送费用: " + total); // 期望值: (1.00 + 10.50 + 2.25 + 5.00) + (0 + 7.00 + 1.50 + 3.00) + (0) + (0) + (2.00) = 32.25
    }
}

代码解析
  1. entries.stream(): 创建CartEntry对象的流程。
  2. mapToDouble(entry -> { ... }): 这是核心部分。对于流中的每个Cartentry对象,我们执行映射操作,将其转换为double值。
    • 在映射函数中,我们初始化一个BigDecimal变量curententrytotal来积累当前cartentry的所有相关费用。
    • 链式访问及Optional处理: 为了安全访问深层嵌套的对象字段,避免NullpointerException,我们使用了Optional.ofNullable()。
      • Optional.ofNullable(entry.getFulfillment()):如果fulfillment不是null,则返回包含它的optional;否则,返回Optional.empty()。
      • .map(Fulfillment::getStoreDelivery):如果上一步的Optional值得,则继续映射到Storedelivery对象。
      • .map(StoreDelivery::getCost):继续映射到cost字段。
      • .orElse(BigDecimal.ZERO):如果任何一步的映射导致Optional为空(即中间对象或最终字段为null),则返回BigDecimal.作为替代值,ZERO确保求和操作不会中断。
    • currentEntryTotal.add(...): 在currentEntryTotal中累计通过Optional安全获得的BigDecimal值。
    • .doubleValue(): 返回前,将最终BigDecimal总和转换为double类型,供maptodouble使用。
  3. .sum(): 最终求和maptodouble生成的所有double值,并获得所有购物车项目的总配送费用。
注意事项
  1. BigDecimal的精度: BigDecimal而不是double或float,总是优先考虑货币或任何需要精确计算的值。doubleValue()在最终求和之前,方法将BigDecimal转换为double。如果对最终结果的准确性有很高的要求,可以考虑使用stream。<BigDecimal>并配合reduce操作来保持bigdecimal的精度,但这将有点复杂。

    // 保持BigDecimal精度的求和示例
    BigDecimal totalBigDecimal = entries.stream()
        .map(entry -> {
            BigDecimal currentEntryTotal = BigDecimal.ZERO;
            // ... (同上,通过Optional获取add的所有BigDecimal字段)
            return currentEntryTotal;
        })
        .reduce(BigDecimal.ZERO, BigDecimal::add);
    System.out.println("所有购物车条目的总配送费 (BigDecimal): " + totalBigDecimal);

  2. 处理和注释Nulll值:

    • @NotNull和类字段在原始问题中使用@DecimalMin(0.0)等注释。这些注释通常在编译或操作过程中通过验证框架(如JSR)。 303/380 Bean Validation)检查,以确保字段不是null,并满足最小值。
    • 如果这些注释能保证所有BigDecimal字段(如cost,当业务逻辑在这里执行时, deliveryServiceFee, fee)父亲的对象不会是null,BigDecimal类型的字段在未显式赋值时会自动初始化为BigDecimal.ZERO,所以Optional在上述代码中.ofNullable().orElse(BigDecimal.ZERO)通过getter直接访问,可以简化部分。
    • 然而,如果这些保证不完全可靠(例如,对象可以在未经完整验证的情况下创建或修改),或者中间对象(如fulfilment或storedelivery)可能是null,那么使用optional进行防御编程仍然是提高代码强度的最佳实践。本教程中的示例代码已包含此防御处理。
  3. 代码可读性: 当嵌套级别过多时,map操作中的逻辑可能会变得复杂。为了提高可读性,可以考虑将获得单个cartentry总成本的逻辑包装到私人辅助方法中。

总结

通过Java Stream API,我们可以优雅地处理复杂嵌套对象中的数据聚合任务。结合maptodouble和bigdecimal的精确计算,以及optional的防御编程,可以编写高效和强大的代码。在实际开发中,理解数据模型的约束(如注释带来的null值保证)将有助于我们选择最简单和有效的实现方法。

以上是Java Stream API处理嵌套对象字段求和:以购物车条目为例,请关注图灵教育的其他相关文章!