java8 - 映射列表的列表 : check if nested list is null

标签 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();
}

我想返回 Role::id 列表。

如果getAssociationRoles不为空,下面的代码片段将起作用

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

如果getAssociationRoles为空,则抛出NullPointerException

如何防止这种情况发生?

最佳答案

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

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

关于java8 - 映射列表的列表 : check if nested list is null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57817502/

相关文章:

Java 8 lambda 用于为每个部门选择最高薪员工

java - ConEmu (CMD) 无法识别这些 un​​icode 字符?

python - python 循环中的 lambda 运算符

c# - Expression<Func<TModel,string>> 到 Expression<Action<TModel>> "Getter"到 "Setter"

java - 将匿名类转换为 lambda 后代码表现不同

java - 如何获得 Java 8 年表的纪元限制?

Java Double 和 Float 数学表现异常

Java、Netty、TCP和UDP连接集成 : No buffer space available for UDP connection

java - Hibernate通过非主键获取实体并更新它+ Spring mvc

java - 如何用java迭代每n个元素?