Elegant way to invert a map in Scala

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

    You could invert a map using:

    val i = origMap.map({case(k, v) => v -> k})
    

    The problem with this approach is that if your values, which have now become the hash keys in your map, are not unique you will drop the duplicate values. To illustrate:

    scala> val m = Map("a" -> 1, "b" -> 2, "c" -> 3, "d" -> 1)
    m: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3, d -> 1)
    
    // Notice that 1 -> a is not in our inverted map
    scala> val i = m.map({ case(k , v) => v -> k})
    i: scala.collection.immutable.Map[Int,String] = Map(1 -> d, 2 -> b, 3 -> c)
    

    To avoid this you can convert your map to a list of tuples first, then invert, so that you don't drop any duplicate values:

    scala> val i = m.toList.map({ case(k , v) => v -> k})
    i: List[(Int, String)] = List((1,a), (2,b), (3,c), (1,d))
    

提交回复
热议问题