首页 > 解决方案 > 如何将 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()

标签: javaoptional

解决方案


您可以将多个调用链接起来,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 非常相似


推荐阅读