Вы можете сделать это, используя flatMap
и map
instaead как:
if (null != roles) {
authorities = roles.stream()
.flatMap(role -> role.getPermissions().stream()) // Stream<Permission>
.map(permission ->
new SimpleGrantedAuthority("ROLE_" + permission.getLabel())) // Stream<SimpleGrantedAuthority>
.collect(Collectors.toList());
}
В коде цикла for
вы не отфильтровываете и не выполняете никакие итерации на основе условия и выполняете итерацииво всех списках, следовательно, вам не требуется filter
здесь.
И, используя вышеуказанный полный метод, можно записать как:
public List<GrantedAuthority> toAuthorities(Set<Role> roles) {
return roles == null ? new ArrayList<>() : roles.stream()
.flatMap(role -> role.getPermissions().stream())
.map(permission -> new SimpleGrantedAuthority("ROLE_" + permission.getLabel()))
.collect(Collectors.toList());
}
Или как предложено shmosel , со ссылками на метод это можно преобразовать как:
return roles == null ? new ArrayList<>() : roles.stream()
.map(Role::getPermissions)
.flatMap(Collection::stream)
.map(Permission::getLabel)
.map("ROLE_"::concat)
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());