简体   繁体   中英

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

Consider this object:

final List<ApplicationUser> output = Arrays.asList(

    new ApplicationUser() {

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


    }
);

public interface Role {
    String getId();
}

I want to return a List of Role::id.

The snippet below works if getAssociationRoles is not null

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

Hovever a NullPointerException is thrown if getAssociationRoles is null.

How can I prevent this ?

Just add a filter to filter out the null association roles:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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