scalascala-collections

Elegant way to invert a map in Scala


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:

(Map() ++ origMap.map(kvp=>(kvp._2->kvp._1)))

Anybody have a more elegant approach?


Solution

  • Assuming values are unique, this works:

    (Map() ++ origMap.map(_.swap))
    

    On Scala 2.8, however, it's easier:

    origMap.map(_.swap)
    

    Being able to do that is part of the reason why Scala 2.8 has a new collection library.