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 ?
getAssociationRoles()to never returnnull. UseCollections.emptyList()as default value.getAssociationRoles(). That should be the actual answer to the question.nullis 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.