0

I have a Set[Set[String], Set[String]] of java.util.Set type which I want to convert to scala.immutable.Map[String, scala.immutable.Set[String]]. The mapping is like each element of the first set inside the outermost set maps to the second set of the outermost set. I tried a for expression:

for (groupRole <- groupRoleAccess;
     user <- groupService.getGroup(groupRole.groupId).getUsers.asScala;
     permissions = roleService.getRole(groupRole.roleId).getPermissions.asScala)
  yield Map(user, permissions) 

where groupRoleAccess is the outermost set,

getUsers gives me the first set inside the outermost set,

getPermissions gives me the second set inside the outermost set

However, what I get is a Set[Map[String, Set[String]]] and of the collection.mutable.Set type. Do I again apply a function to change this Set to the Map I need or is there a better way out?

1
  • Could you please give an example, i.e. from the Scala REPL, of a value having type Set[Set[String], Set[String]]? Also, can you please an example of desiredFunction(input example) === desiredOutput? Example: addOne(4) === 5 Commented Jun 30, 2016 at 13:57

2 Answers 2

1

You want to change your yield to yield user -> permissions. That will give you a Set[(String, Set[String])]. You then do .toMap on it, and voila!

Alternatively (I am not recommending this, but just for the sake of completeness), you can just do .reduce(_ ++ _) on the result of what you have. That'll merge your set of maps into one map. (Note, if there is a possibility, that the result is going to be empty, you'll want foldLeft(Map.empty[String, Set[String]]){ _ ++ _ } instead of reduce).

Sign up to request clarification or add additional context in comments.

Comments

0

Right now what you are doing is collecting Map[String, Set[String]] which the for loop adds to a set.

One way to accomplish what you want to do is to output the results of the for loop into a tuple and then use the toMap function

val x = for( user <- ...; permissions <- ...) yield (user, permissions) 
x.toMap

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.