Elegant way to invert a map in Scala

AlexeyMK picture AlexeyMK · Feb 25, 2010 · Viewed 29.1k times · Source

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?

Answer

Daniel C. Sobral picture Daniel C. Sobral · Feb 26, 2010

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.