【问题标题】:How to check null on Object where List<Object> Object contains Object? [duplicate]如何在 List<Object> Object 包含 Object 的 Object 上检查 null? [复制]
【发布时间】:2020-11-07 01:40:23
【问题描述】:

例如:

public class HelpMetric {
    private String metricId;
    private String supportType;
    private RequestSupportVo requestSupport;
} 

public class RequestSupportVo {
    private String requestSupportId;
}

public List<HelpMetric> getHelpMetric(String metricId) {
List<PolHelpMetric> list =helpMetricMapper.hlpMetricListToPolHelpMetricVoList(all);
        list.forEach(x -> {
            if (x.getRequestSupport() != null) {
                if (x.getRequestSupport().getRequestSupportId() != null) {
}
}
}

如果使用 Java 8 进行条件空检查,我如何优化上述代码二

if (x.getRequestSupport() != null) { if (x.getRequestSupport().getRequestSupportId() != null) {

【问题讨论】:

  • 你听说过&amp;&amp;吗?
  • 是的,但你知道在这种情况下 if (x.getRequestSupport() != null && x.getRequestSupport().getRequestSupportId() != null) { }。如果 x.getRequestSupport().getRequestSupportId() 它的 (x.getRequestSupport()) 值为 null 意味着我们将获得空指针异常..所以我们不能保持 && 条件
  • 对。有什么问题? &amp;&amp; 如果第一个条件评估为假,则短路。你不会得到 NullPointerException。
  • 如果你想使用流 api 做条件,那么 list.filter(1st cond).filter(2nd cond).forEach(...)

标签: java java-8


【解决方案1】:

Java 的逻辑运算符与许多其他语言中的逻辑运算符一样,表现出short-circuit evaluation 行为。

所以一个像下面这样的条件块:

if (a.getB() != null) {
   if (a.getB().getC() != null) {
       // ...
   }
}

可以安全地改写为:

if (a.getB() != null && a.getB().getC() != null) {
   // ...
}

由于短路行为,如果第一个条件失败,则不会评估第二个条件,并且不会冒险抛出NullPointerException

【讨论】:

    猜你喜欢
    • 2020-03-25
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多