Merge maps by key

前端 未结 8 2128
不思量自难忘°
不思量自难忘° 2020-12-01 05:14

Say I have two maps:

val a = Map(1 -> \"one\", 2 -> \"two\", 3 -> \"three\")
val b = Map(1 -> \"un\", 2 -> \"deux\", 3 -> \"trois\")
         


        
8条回答
  •  一生所求
    2020-12-01 05:54

    scala.collection.immutable.IntMap has an intersectionWith method that does precisely what you want (I believe):

    import scala.collection.immutable.IntMap
    
    val a = IntMap(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four")
    val b = IntMap(1 -> "un", 2 -> "deux", 3 -> "trois")
    
    val merged = a.intersectionWith(b, (_, av, bv: String) => Seq(av, bv))
    

    This gives you IntMap(1 -> List(one, un), 2 -> List(two, deux), 3 -> List(three, trois)). Note that it correctly ignores the key that only occurs in a.

    As a side note: I've often found myself wanting the unionWith, intersectionWith, etc. functions from Haskell's Data.Map in Scala. I don't think there's any principled reason that they should only be available on IntMap, instead of in the base collection.Map trait.

提交回复
热议问题