【问题标题】:What's the best way to avoid null using inside lambda using Java 8? [duplicate]使用 Java 8 在 lambda 内部避免使用 null 的最佳方法是什么? [复制]
【发布时间】:2017-04-27 19:42:39
【问题描述】:

我有这段代码,我正在尝试找出使用 Java 8 避免空指针异常的最佳方法是什么?

promotion.forEach(item ->
    item.getDiscount().getPromotions().forEach(promotion -> {
        // logic code here
    })
);

【问题讨论】:

  • 潜在的NPE在哪里?与 lambdas 有什么关系?
  • 小心 - 这里有两个名为 promotion 的变量。
  • 你可以使用Optional.ofNullable
  • Optional 专门包含在 Java 平台库中,用于处理流中可能出现 null 值的情况。
  • 最好的办法是不要有空值。

标签: java lambda java-8


【解决方案1】:
promotion.stream()
    .map(item->item.getDiscount()).filter(Objects::nonNull)
    .map(discount->discount.getPromotions()).filter(Objects::nonNull)
    .forEach(innerPromotion->{//logic code});

您可以在逻辑代码中使用它们之前过滤掉所有的空元素,这样只有非空元素才能运行逻辑代码。

【讨论】:

  • .filter(discount - discount != null) 有必要吗? .map(discount->discount.getPromotions()) 不工作吗?
  • 如果 item.getDiscount() 返回 null 那么你在执行 .map(discount.getPromotions()) 时会得到 NPE,除非你先过滤掉 null 折扣值
  • 我认为 Discount 类应该被设计为从不从像 getPromotions 这样的集合方法返回 null;当促销活动为零时,始终返回一个空集合。
  • 完美答案,让foreach不会抛出空指针异常。
【解决方案2】:

避免 NullPointerExceptions 的最佳方法是避免空值。在您的示例中,请确保所有方法都不会返回 null。

您有多种选择,而不是返回 null:

  • 抛出异常。例如,如果方法的输入导致被零除,您可以抛出异常而不是返回 null。
  • 返回一个空的可选。例如,可以将返回 String 的方法更改为返回 Optional。当没有 String 要返回时,返回 Optional.empty()
  • 返回一个空的Collection(例如当结果类型为List时,如果没有找到结果则返回一个空的List,而不是返回null)
  • 返回自定义结果类型,能够反映结果。例如,在进行验证时,您可以返回表示成功/失败和错误消息的 ValidationResult,而不是在没有错误时返回 null 错误消息

【讨论】:

    【解决方案3】:

    你在想Optional之类的东西吗:

    item.getDiscount().getPromotions().stream().forEach(promotion ->     
        Optional.ofNullable(promotion).ifPresent(p -> {
            // logic code 
        } )
    );
    

    编辑:如果item.getDiscount() 可能为空,那么您可以尝试:

    Optional.ofNullable(item.getDiscount()).ifPresent(d -> 
        d.getPromotions().stream().forEach(promotion ->     
            Optional.ofNullable(promotion).ifPresent(p -> {
                // logic code 
            } )
        )
    );
    

    【讨论】:

    • 在 .getPromotions() 上它会提高 NPE 不是吗?
    猜你喜欢
    • 2011-03-22
    • 2016-11-12
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多