簡體   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