Learning Scala currently and needed to invert a Map to do some inverted value->key lookups. I was looking for a simple way to do this, but came up with only:
Starting Scala 2.13, in order to swap key/values without loosing keys associated to same values, we can use Maps new groupMap method, which (as its name suggests) is an equivalent of a groupBy and a mapping over grouped items.
Map(1 -> "a", 2 -> "b", 4 -> "b").groupMap(_._2)(_._1)
// Map("b" -> List(2, 4), "a" -> List(1))
This:
groups elements based on their second tuple part (_._2) (group part of groupMap)
maps grouped items by taking their first tuple part (_._1) (map part of groupMap)
This can be seen as a one-pass version of map.groupBy(_._2).mapValues(_.map(_._1)).