考虑该对象:
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 不为空,则以下代码段有效
final List<String> rolesId = applicationUsers
.stream()
.map(ApplicationUser::getAssociationRoles)
.flatMap(List::stream)
.map(Role::getId)
.collect(Collectors.toList());
如果 getAssociationRoles 为null,则会抛出 NullPointerException 。
如何防止这种情况?
答案 0 :(得分:1)
只需添加一个filter
即可过滤出空关联角色:
final List<String> rolesId = applicationUsers
.stream()
.map(ApplicationUser::getAssociationRoles)
.filter(Objects::nonNull) <------- here!
.flatMap(List::stream)
.map(Role::getId)
.collect(Collectors.toList());