java - 如何将 Optional.ofNullable 下的空指针作为嵌套处理?
问题描述
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());
注意:当您使用 Java 9 或更高版本时,您编写.orElseGet(Collections::emptyList).stream()
的可能会缩短为简单。.stream()
第二个注意事项:Stream
在我看来,A 在这里并没有什么意义,正常的操作就Optional
足够了,因为 API 非常相似
推荐阅读
- jquery - 将 div 与下一个 div 交换
- python-3.x - 在 pandas 中设置 csv 文件的子集
- javascript - 如何指定要在角度中包含代码覆盖文件的文件夹?
- sql - 有没有办法改变这个 BigQuery 自联接以使用窗口函数?
- c# - C# 中异步方法的匿名对象任务的正确返回类型
- c# - 从 C# 调用正在运行的访问应用程序的 msaccess 方法
- docker - 如何使用当前主机用户运行 Windows docker 容器?- 泊坞窗
- c# - 当一个请求超时时,HttpClient Parallel Requests Timeout 使用 Task.WhenAll
- python-3.x - 向轴添加额外维度
- google-apps-script - 在电子表格中的所有列上运行的累积和