将双嵌套for循环重写为Java 8流 [英] Rewrite double nested for loop as a Java 8 stream
问题描述
我有以下Java方法:
I have the following Java method:
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流重写它.迄今为止我最大的尝试:
I'm trying to rewrite it using Java 8 streams. My best attempt thus far:
public List<GrantedAuthority> toAuthorities(Set<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
if (null != roles) {
roles.stream().filter(role -> ???).collect(Collectors.toList());
}
return authorities;
}
但是我对流过滤器中的内容(替换为???
)感到迷茫……有什么想法吗?
But I'm at a loss as to what I put in the stream filter (substituting ???
)...any ideas?
推荐答案
您可以使用flatMap
和map
instaead作为:
You can do it using flatMap
and map
instaead as :
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
.
In the for
loop code, you are not filtering out/in any iteration based on a condition and iterating throughout the lists, hence you don't require a filter
here.
使用上述方法,您的完整方法可以写成:
And using the above your complete method could be written as :
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建议,使用方法引用,可以将其转换为:
Or as suggested by shmosel, with method references this could be transformed as :
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());
这篇关于将双嵌套for循环重写为Java 8流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!