# 在 Scala 中合并两个 map，然后将具有相同键的值相加

Suraj P 2023年1月30日

## 在 Scala 中使用 `++` 运算符合并两个 map

``````map1.++(map2)
``````

``````object Main {
def main(args: Array[String])
{
//let's assume a mapping from Student -> marks

val map1_english = Map("Tony" -> 50, "Ruby" -> 89)
val map2_maths = Map("Tony"->77,"Ruth" -> 100, "Ben" -> 78)

println("Map1 : " + map1_english)
println("Map2 : " + map2_maths)

// merging the map
val mergedMap = map1_english.++(map2_maths)

println("Class marks are : " + mergedMap)
}
}
``````

``````Map1 : Map(Tony -> 50, Ruby -> 89)
Map2 : Map(Tony -> 77, Ruth -> 100, Ben -> 78)
Class marks are : Map(Tony -> 77, Ruby -> 89, Ruth -> 100, Ben -> 78)
``````

## 合并 map 并对具有相同键的值求和

### 方法一：

``````object Main {
def main(args: Array[String])
{

val map1_english = Map("Tony" -> 50, "Ruby" -> 89)
val map2_maths = Map("Tony"->77,"Ruby" -> 100, "Ben" -> 78)

val mergedList = map1_english.toList ++ (map2_maths.toList)

println("Merged List : " + mergedList)

val mergedKeys = mergedList.groupBy(_._1).map{case (k,v) => k -> v.map(_._2).sum}

println("Merged Map with summed up values : " + mergedKeys)
}
}
``````

``````Merged List : List((Tony,50), (Ruby,89), (Tony,77), (Ruby,100), (Ben,78))
Merged Map with summed up values : Map(Ruby -> 189, Ben -> 78, Tony -> 127)
``````

### 方法二：

``````object Main {
def main(args: Array[String])
{
val map1_english = collection.immutable.HashMap("Tony" -> 50, "Ruby" -> 89)
val map2_maths = collection.immutable.HashMap("Tony"->77,"Ruby"-> 100, "Ben"->78)

val merged = map1_english.merged(map2_maths)({ case ((k,v1),(_,v2)) =>(k,v1+v2)})

println("Merged Map with summed up values : " + merged)
}
}
``````

``````Merged Map with summed up values : Map(Ruby -> 189, Tony -> 127, Ben -> 78)
``````

A technophile and a Big Data developer by passion. Loves developing advance C++ and Java applications in free time works as SME at Chegg where I help students with there doubts and assignments in the field of Computer Science.