Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use java stream map inside java stream filter

I have 2 arrays and want to make a list of role.getRoleName() only with elements that are in both arrays using streams.

final List<String> roleNames = new ArrayList<>();
roleNames = Arrays.stream(roles).filter(role -> role.getRoleId() 
== Arrays.stream(permissions).map(permission -> permission.getRoleId()));

when I write the above code I get

Operator '==' cannot be applied to 'int', 'java.util.stream.Stream'

I understand the error, but I don't know the solution of how to make the permissions stream in only permission.getRoleId integers.

like image 933
Milan Panic Avatar asked Apr 07 '26 00:04

Milan Panic


1 Answers

There is no way to compare such incompatible types as int and Stream.

Judging from what you've shown, Stream#anyMatch might a good candidate.

roleNames = Arrays.stream(roles)
    .map(Role::getRoleId)
    .filter(id -> Arrays.stream(permissions).map(Role::getRoleId).anyMatch(p -> p.equals(id)))
    .collect(Collectors.toList());

This part Arrays.stream(permissions).map(Role::getRoleId) may be pre-calculated and stored into a Set.

final Set<Integer> set = Arrays.stream(permissions)
                               .map(Role::getRoleId)
                               .collect(Collectors.toSet());

roleNames = Arrays.stream(roles)
                  .filter(role -> set.contains(role.getRoleId()))
                  .map(Role::getRoleName)
                  .collect(Collectors.toList());
like image 192
Andrew Tobilko Avatar answered Apr 08 '26 14:04

Andrew Tobilko