Scala Map合并并在键相同时对值求和

时间:2018-03-28 03:37:12

标签: scala dictionary

如何合并如下地图:

val a = Map("a" -> 1, "b" -> 2)
val b = Map("b" -> 3, "c" -> 6)
合并后

var c = Map("a" -> 1, "b" -> 5, "c" -> 6)

1 个答案:

答案 0 :(得分:0)

 val a = Map("a" -> 1, "b" -> 2) 
 val b = Map("b" -> 3, "c" -> 6)
 val c = a.map {
   case (key, value) => key -> (value + b.getOrElse(key, 0))
 } ++ b.filterKeys(bKey => !a.keySet.contains(bKey))

这应该有效,但如果没有......我发现我认为你的问题是重复的:Best way to merge two maps and sum the values of same key?

在那里你会看到其他可能的解决方案......

(map1.keySet ++ map2.keySet).map {i=> (i,map1.getOrElse(i,0) + map2.getOrElse(i,0))}.toMap


map1 ++ map2.map { case (k,v) => k -> (v + map1.getOrElse(k,0)) }

val m1 = Map(1 -> 1.0, 3 -> 3.0, 5 -> 5.2)
val m2 = Map(0 -> 10.0, 3 -> 3.0)
val merged = (m2 foldLeft m1) (
  (acc, v) => acc + (v._1 -> (v._2 + acc.getOrElse(v._1, 0.0)))
)

还有更多