Elegant way to invert a map in Scala

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

    Mathematically, the mapping might not be invertible (injective), e.g., from Map[A,B], you can't get Map[B,A], but rather you get Map[B,Set[A]], because there might be different keys associated with same values. So, if you are interested in knowing all the keys, here's the code:

    scala> val m = Map(1 -> "a", 2 -> "b", 4 -> "b")
    scala> m.groupBy(_._2).mapValues(_.keys)
    res0: Map[String,Iterable[Int]] = Map(b -> Set(2, 4), a -> Set(1))
    

提交回复
热议问题