Reputation: 696
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?
Upvotes: 0
Views: 133
Reputation: 40500
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
).
Upvotes: 1
Reputation: 1500
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
Upvotes: 0