EDIT: A fixed answer to include what Mart rightly pointed out. My answer is a little longer than his, as I try to go through every step, and not use the magic provided by flatMaps for educational purposes, its more straightforward :)
I'm not sure about your notation. I assume you have something like:
val myMap = Map[T, Set[T]] (
x -> Set(b, c),
y -> Set(b, d, e),
z -> Set(d, f, g, h)
)
:
val instances = for {
keyValue <- myMap.toList
value <- keyValue._2
}
yield (value, keyValue._1)
:
(b, x), (c, x), (b, y) ...
:
val groupedLookups = instances.groupBy(_._1)
:
b -> ((b, x), (b, y)),
c -> ((c, x)),
d -> ((d, y), (d, z)) ...
, . :
val reverseLookup = groupedLookup.map(_._1 -> _._2.map(_._2))
, , , .
.
( , , )