0

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 ?

4
  • 4
    Just fix getAssociationRoles() to never return null. Use Collections.emptyList() as default value. Commented Sep 6, 2019 at 7:43
  • 1
    @Holger The first thing that came to my mind after reading getAssociationRoles(). That should be the actual answer to the question. Commented Sep 6, 2019 at 9:13
  • @Holger what if the object is not in my domain ? Commented Sep 6, 2019 at 9:21
  • 3
    The rule that collections should not be null is a universal one. Violating it is bad coding style. You may send a bug report to whoever is responsible for the method. Besides that, you have an answer that shows how to deal with such bad methods. Commented Sep 6, 2019 at 9:32

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

1 Comment

A better suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.