繁体   English   中英

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

[英]java8 - map a list of a list: check if nested list is null

考虑这个对象:

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不为null,则以下代码段有效

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

如果getAssociationRoles为null,则抛出NullPointerException

我该如何预防呢?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM