java8-映射列表的列表:检查嵌套列表是否为null

时间:2019-09-06 07:24:05

标签: java lambda java-8

考虑该对象:

final List<ApplicationUser> output = Arrays.asList(

    new ApplicationUser() {

        @Override
        public List<Role> getAssociationRoles() {
            //return null;
            return Arrays.listOf(...);              
        }


    }
);

public interface Role {
    String getId();
}

我想返回一个角色列表:: id。

如果 getAssociationRoles 不为空,则以下代码段有效

final List<String> rolesId = applicationUsers
            .stream()
            .map(ApplicationUser::getAssociationRoles)
            .flatMap(List::stream)
            .map(Role::getId)
            .collect(Collectors.toList());

如果 getAssociationRoles 为null,则会抛出 NullPointerException

如何防止这种情况?

1 个答案:

答案 0 :(得分:1)

只需添加一个filter即可过滤出空关联角色:

final List<String> rolesId = applicationUsers
    .stream()
    .map(ApplicationUser::getAssociationRoles)
    .filter(Objects::nonNull) <------- here!
    .flatMap(List::stream)
    .map(Role::getId)
    .collect(Collectors.toList());