rajadilipkolli rajadilipkolli - 4 months ago 20
Java Question

How to perform multiple operations on same custom object using Java 8

I have a Role object which contains roleName, roleId and rolePermissions which is also a list of permissions object.

Now I want to retrieve roleName and add it to Set and from permissionList retrieve all permissions and add to the same Set to achieve this using pre Java 8 I have achieved using below code

for (Role role : roleList) {
authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
List<Permission> permissions = role.getPermissions();
for (Permission permission : permissions) {
.add(new SimpleGrantedAuthority("ROLE_" + permission.getName()));

Using Java8 I have achieved the same using

Set<GrantedAuthority> authorities = new HashSet<>();
roleList.stream().parallel().peek(role -> authorities.add(new SimpleGrantedAuthority(role.getRoleName())))
.forEach(role -> role.getPermissions()
.forEach(p -> authorities.add(new SimpleGrantedAuthority("ROLE_" + p.getName()))));

I feel we are not leveraging full Java8 features and above is not correct way to achieve . How to achieve the same more effectively?


Since the end goal is to obtain a general set which is not sorted, (and as was pointed out to me on a very related question) you can also have:

Set<GrantedAuthority> authorities = Stream.concat(
  roleList.stream().map(role -> new SimpleGrantedAuthority(role.getRoleName())),
  roleList.stream().flatMap(role -> role.getPermissions().stream()).map(p -> new SimpleGrantedAuthority("ROLE_" + p.getName()))

which only concatenates a stream formed by the role names and the name of each permission in a role.