Elegant way to invert a map in Scala

前端 未结 10 594
慢半拍i
慢半拍i 2020-12-02 13:49

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:



        
10条回答
  •  感动是毒
    2020-12-02 14:24

    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.

提交回复
热议问题