[英]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.