Elegant way to invert a map in Scala

前端 未结 10 562
慢半拍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:34

    You can avoid the ._1 stuff while iterating in few ways.

    Here's one way. This uses a partial function that covers the one and only case that matters for the map:

    Map() ++ (origMap map {case (k,v) => (v,k)})
    

    Here's another way:

    import Function.tupled        
    Map() ++ (origMap map tupled {(k,v) => (v,k)})
    

    The map iteration calls a function with a two element tuple, and the anonymous function wants two parameters. Function.tupled makes the translation.

提交回复
热议问题