你可以使用flatMap和map instaead来做到:
if (null != roles) {
authorities = roles.stream()
.flatMap(role -> role.getPermissions().stream()) // Stream
.map(permission ->
new SimpleGrantedAuthority("ROLE_" + permission.getLabel())) // Stream
.collect(Collectors.toList());
}
在for循环代码中,您不会基于条件过滤/在任何迭代中并在整个列表中进行迭代,因此您不需要在此处使用过滤器.
使用上面的完整方法可以写成:
public List toAuthorities(Set roles) {
return roles == null ? new ArrayList<>() : roles.stream()
.flatMap(role -> role.getPermissions().stream())
.map(permission -> new SimpleGrantedAuthority("ROLE_" + permission.getLabel()))
.collect(Collectors.toList());
}
或者作为suggested by 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());