Elegant way to invert a map in Scala

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

    1. Inverse is a better name for this operation than reverse (as in "inverse of a mathematical function")

    2. I often do this inverse transformation not only on maps but on other (including Seq) collections. I find it best not to limit the definition of my inverse operation to one-to-one maps. Here's the definition I operate with for maps (please suggest improvements to my implementation).

      def invertMap[A,B]( m: Map[A,B] ) : Map[B,List[A]] = {
        val k = ( ( m values ) toList ) distinct
        val v = k map { e => ( ( m keys ) toList ) filter { x => m(x) == e } }
        ( k zip v ) toMap
      }
      

    If it's a one-to-one map, you end up with singleton lists which can be trivially tested and transformed to a Map[B,A] rather than Map[B,List[A]].

提交回复
热议问题