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

forEach循环中高效空值检查方法?现有代码触发空指针异常

问题分析

你当前的空值检查只覆盖了productId,但实际存在多个可能触发异常的风险点:common.getProducts()可能为null、products是空列表(调用get(0)会抛索引越界异常)、products.get(0)本身为null,这些情况都会导致NullPointerException或索引越界异常。

高效空值检查方案

方案1:分步检查(逻辑清晰,无语法糖依赖)

通过逐层拆解链式调用,对每一个可能为空的对象/集合做前置检查:

commonEntities.forEach(common -> {
    Long contractedQty = getContractedQty(common.getProducts());
    String productName = StringUtils.EMPTY;
    
    List<Product> products = common.getProducts();
    // 先判断集合是否非空且不为null
    if (products != null && !products.isEmpty()) {
        Product firstProduct = products.get(0);
        if (firstProduct != null) {
            String productId = firstProduct.getProductId();
            if (productId != null) {
                Product mappedProduct = productMap.get(productId);
                // 检查map中取出的对象是否为null
                if (mappedProduct != null) {
                    productName = mappedProduct.getName();
                }
            }
        }
    }

    // 后续业务逻辑
    .......
});

方案2:使用Java 8+ Optional简化(优雅简洁)

利用Optional的链式调用自动终止空值流程,避免多层if嵌套:

commonEntities.forEach(common -> {
    Long contractedQty = getContractedQty(common.getProducts());
    String productName = Optional.ofNullable(common.getProducts())
            .filter(list -> !list.isEmpty()) // 过滤空集合
            .map(list -> list.get(0)) // 取第一个元素
            .map(Product::getProductId) // 取productId
            .map(productMap::get) // 从map中获取对应Product
            .map(Product::getName) // 取商品名称
            .orElse(StringUtils.EMPTY); // 所有环节为空时返回默认值

    // 后续业务逻辑
    .......
});

方案3:抽取工具方法(复用性强)

如果多处需要类似逻辑,可将空值检查逻辑封装为工具方法,提升代码复用性:

// 单独封装的工具方法
private String getProductName(List<Product> products, Map<String, Product> productMap) {
    return Optional.ofNullable(products)
            .filter(list -> !list.isEmpty())
            .map(list -> list.get(0))
            .map(Product::getProductId)
            .map(productMap::get)
            .map(Product::getName)
            .orElse(StringUtils.EMPTY);
}

// 循环中直接调用
commonEntities.forEach(common -> {
    Long contractedQty = getContractedQty(common.getProducts());
    String productName = getProductName(common.getProducts(), productMap);

    // 后续业务逻辑
    .......
});
注意事项
  • 永远不要假设集合非空,必须先检查!products.isEmpty()再调用get(0)
  • 从Map中取值后必须检查是否为null,避免mappedProduct.getName()触发NPE
  • Optional方案适合Java 8及以上版本,在可读性和代码简洁性上更有优势

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 03:33:11