Elegant way to invert a map in Scala

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

    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)).

提交回复
热议问题