3

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.

2
  • How about using .equals? and that too on roleId. If permission.getRoleId are integers, why do you plan to collect similar data as List<String>? Commented Sep 9, 2019 at 8:43
  • roleId is an int and roleName is string. I want to add roleName in the list Commented Sep 9, 2019 at 8:44

2 Answers 2

4

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());
Sign up to request clarification or add additional context in comments.

Comments

3

What you can do is collect unique roleIds for the array of Permissions into a Set as a computed result and perform a contains check as you iterate through the array of Roles. This could be done as :

final Set<Integer> uniqueRoleForPermissions = Arrays.stream(permissions)
        .map(Permission::getRoleId)
        .collect(Collectors.toSet());
final List<String> roleNames = Arrays.stream(roles)
        .filter(role -> uniqueRoleForPermissions.contains(role.getRoleId()))
        .map(Role::getRoleName)
        .collect(Collectors.toList());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.