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?

rrrocky
  • 696
  • 1
  • 11
  • 27
  • 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` – Kevin Meredith Jun 30 '16 at 13:57

2 Answers2

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).

Dima
  • 39,570
  • 6
  • 44
  • 70
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
Benjamin Kadish
  • 1,472
  • 11
  • 20