Elegant way to invert a map in Scala

前端 未结 10 596
慢半拍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条回答
  •  旧时难觅i
    2020-12-02 14:25

    I came here looking for a way to invert a Map of type Map[A, Seq[B]] to Map[B, Seq[A]], where each B in the new map is associated with every A in the old map for which the B was contained in A's associated sequence.

    E.g.,
    Map(1 -> Seq("a", "b"), 2-> Seq("b", "c"))
    would invert to
    Map("a" -> Seq(1), "b" -> Seq(1, 2), "c" -> Seq(2))

    Here's my solution :

    val newMap = oldMap.foldLeft(Map[B, Seq[A]]().withDefaultValue(Seq())) {
      case (m, (a, bs)) => bs.foldLeft(m)((map, b) => map.updated(b, m(b) :+ a))
    }
    

    where oldMap is of type Map[A, Seq[B]] and newMap is of type Map[B, Seq[A]]

    The nested foldLefts make me cringe a little bit, but this is the most straightforward way I could find to accomplish this type of inversion. Anyone have a cleaner solution?

提交回复
热议问题