重写双嵌套for循环作为一个Java 8流

hotmeatballsoup:

我有以下的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;
}

但我茫然,什么我把在流过滤器(代???)...任何想法?

也:

你可以用它做flatMapmapinstaead为:

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());

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章