Error trying to convert nested for loop into Java 8 threads

I am trying to convert a nested loop thread to java 8 threads.

Loop implementation

private Set<String> getAllowRolesFromInheritedPolicy(String userId, List<Policy> allowedPoliciesThisCustomer) {

    Set<String> allowedRolesThisUser = Sets.newHashSet();

    for (Policy policy : allowedPoliciesThisCustomer) {
        Map<String, Role> roles = policy.getRoles();
        for (Role role : roles.values()) {
            if (role.getUsers().contains(userId)) {
                allowedRolesThisUser.add(role.getRoleName());                   
            }
        }
    }

The code is role.getUsers()returned List<String>.

Stream implementation

I am trying to change the for loop in java 8 streams:

Set<String> allowedRolesThisUser = Sets.newHashSet(allowedPoliciesThisCustomer.stream()
                                       .map(policy -> policy.getRoles().values())
                                       .filter(role -> role.getUsers().contains(userId))
                                       .collect(Collectors.toList()));

But the compiler says:

error: cannot find symbol : .filter(role -> role.getUsers().contains(userId))
symbol:   method getUsers(), location: variable role of type Collection<Role>

Rolehas a function getUsers, Collection<Role>no. What to do to make this conversion correct?

Thank.

+4
source share
2 answers

Decision

private static Set<String> streamImplementation(final String userId, 
  final List<Policy> allowedPoliciesThisCustomer) {

  return allowedPoliciesThisCustomer.stream()
    .map(Policy::getRoles)
    .map(Map::values)
    .flatMap(Collection::stream)
    .filter(r -> r.getUsers().contains(userId))
    .map(Role::getRoleName)
    .collect(Collectors.toSet());
}

Explanation

When you get the values ​​on the map, you need to flatten the map. This is done in the next two lines.

.map(Map::values)
.flatMap(Collection::stream)

This ensures that the type Roleis correctly ported.

Full SSCCE

package com.stackoverflow;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static me.karun.Policy.policy;
import static me.karun.Role.role;
import static org.assertj.core.api.Assertions.assertThat;

public class PoliciesTest {

  @Test
  public void streamImplementation_whenComparedWithALoopImplementation_thenShouldReturnTheSameResult() {
    final String userId = "user-1";
    final Role role1 = role("role-1", "user-1", "user-2");
    final Role role2 = role("role-2", "user-1", "user-3");
    final Role role3 = role("role-3", "user-2", "user-3");
    final Role role4 = role("role-4", "user-3", "user-4");
    final List<Policy> allowedPoliciesThisCustomer = asList(
      policy(role1, role2),
      policy(role3, role4)
    );
    final Set<String> oldResult = loopImplementation(userId, allowedPoliciesThisCustomer);
    final Set<String> newResult = streamImplementation(userId, allowedPoliciesThisCustomer);

    assertThat(newResult).isEqualTo(oldResult);
  }

  private static Set<String> streamImplementation(final String userId, final List<Policy> allowedPoliciesThisCustomer) {
    return allowedPoliciesThisCustomer.stream()
      .map(Policy::getRoles)
      .map(Map::values)
      .flatMap(Collection::stream)
      .filter(r -> r.getUsers().contains(userId))
      .map(Role::getRoleName)
      .collect(toSet());
  }

  private static Set<String> loopImplementation(final String userId, final List<Policy> allowedPoliciesThisCustomer) {
    final Set<String> allowedRolesThisUser = new HashSet<>();

    for (final Policy policy : allowedPoliciesThisCustomer) {
      final Map<String, Role> roles = policy.getRoles();
      for (final Role role : roles.values()) {
        if (role.getUsers().contains(userId)) {
          allowedRolesThisUser.add(role.getRoleName());
        }
      }
    }

    return allowedRolesThisUser;
  }
}

@RequiredArgsConstructor
@Getter
class Policy {
  private final Map<String, Role> roles;

  static Policy policy(final Role... roles) {
    final Map<String, Role> rolesMap = stream(roles)
      .collect(toMap(Role::getRoleName, identity()));

    return new Policy(rolesMap);
  }
}

@RequiredArgsConstructor
@Getter
class Role {
  private final List<String> users;
  private final String roleName;

  static Role role(final String roleName, final String... users) {
    return new Role(asList(users), roleName);
  }
}

, , !

+7

.

private Set<String> getAllowRolesFromInheritedPolicy(String userId, List<Policy> allowedPoliciesThisCustomer) {
    return allowedPoliciesThisCustomer.stream()
        .flatMap(policy -> policy.getRoles().values().stream())
        .filter(role -> role.getUsers().contains(userId))
        .map(Role::getRoleName)
        .collect(Sets::newHashSet, (set, e) -> set.add(e), (a, b) -> a.addAll(b));
}
+4

Source: https://habr.com/ru/post/1681410/


All Articles