有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在列表<Object>对象包含对象的对象上检查null?

例如:

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) {
}
}
}

如何使用Java8优化上述代码2 if条件null检查

如果(x.getRequestSupport()!=空){ if(x.getRequestSupport()。getRequestSupportId()!=空){


共 (1) 个答案

  1. # 1 楼答案

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

    因此,条件块如下所示:

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

    可以安全地重写为:

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

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