如何处理嵌套在 Optional.ofNullable 下的空指针?
How to Handle Null Pointer under Optional.ofNullable as its nested?
public void createEmployessList() {
List<EmployeeVO> empListVO = Optional.ofNullable(
empListResponse.getEmpListResult().getEmpLite().getEmpInfoLite()
).orElseGet(Collections::emptyList)
.stream()
.map(temp -> {
EmployeeVO empVO = new EmployeeVO();
return empVO;
}).collect(Collectors.toList());
}
如何处理上述代码下的空指针异常,因为它们中的任何一个都可能为空
empListResponse.getEmpListResult().getEmpLite().getEmpInfoLite()
您可以将多个调用链接到 map
,在其中解包对象。
List<EmployeeVO> empListVO = Optional.ofNullable(empListResponse)
.map(e -> e.getEmpListResult())
.map(e -> e.getEmpLite())
.map(e -> getEmpInfoLite())
.stream()
.map(temp -> {
EmployeeVO empVO = new EmployeeVO();
return empVO;
})
.collect(Collectors.toList());
注意:您写的 .orElseGet(Collections::emptyList).stream()
在您使用 Java 9 或更高版本时可能会缩短为 .stream()
。
第二个注意事项:在我看来,Stream
在这里没有任何意义,Optional
上的正常操作就足够了,因为 API 非常相似
public void createEmployessList() {
List<EmployeeVO> empListVO = Optional.ofNullable(
empListResponse.getEmpListResult().getEmpLite().getEmpInfoLite()
).orElseGet(Collections::emptyList)
.stream()
.map(temp -> {
EmployeeVO empVO = new EmployeeVO();
return empVO;
}).collect(Collectors.toList());
}
如何处理上述代码下的空指针异常,因为它们中的任何一个都可能为空 empListResponse.getEmpListResult().getEmpLite().getEmpInfoLite()
您可以将多个调用链接到 map
,在其中解包对象。
List<EmployeeVO> empListVO = Optional.ofNullable(empListResponse)
.map(e -> e.getEmpListResult())
.map(e -> e.getEmpLite())
.map(e -> getEmpInfoLite())
.stream()
.map(temp -> {
EmployeeVO empVO = new EmployeeVO();
return empVO;
})
.collect(Collectors.toList());
注意:您写的 .orElseGet(Collections::emptyList).stream()
在您使用 Java 9 或更高版本时可能会缩短为 .stream()
。
第二个注意事项:在我看来,Stream
在这里没有任何意义,Optional
上的正常操作就足够了,因为 API 非常相似