我有以下 Java 方法:
public List<GrantedAuthority> toAuthorities(Set<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
if (null != roles) {
for (Role role : roles) {
for (Permission permission : role.getPermissions()) {
authorities.add(new SimpleGrantedAuthority("ROLE_" + permission.getLabel()));
}
}
}
return authorities;
}
我正在尝试使用 Java 8 流重写它。迄今为止我的最佳尝试:
public List<GrantedAuthority> toAuthorities(Set<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
if (null != roles) {
roles.stream().filter(role -> ???).collect(Collectors.toList());
}
return authorities;
}
但是我不知道我在流过滤器中放了什么(替换 ???
)...有什么想法吗?
最佳答案
您可以使用 flatMap
和 map
代替:
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());
}
或作为 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());
关于java - 将双嵌套 for 循环重写为 Java 8 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52979975/