Best way to merge two maps and sum the values of same key?

Freewind picture Freewind · Aug 16, 2011 · Viewed 87.2k times · Source
val map1 = Map(1 -> 9 , 2 -> 20)
val map2 = Map(1 -> 100, 3 -> 300)

I want to merge them, and sum the values of same keys. So the result will be:

Map(2->20, 1->109, 3->300)

Now I have 2 solutions:

val list = map1.toList ++ map2.toList
val merged = list.groupBy ( _._1) .map { case (k,v) => k -> v.map(_._2).sum }

and

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

But I want to know if there are any better solutions.

Answer

Rex Kerr picture Rex Kerr · Aug 16, 2011

The shortest answer I know of that uses only the standard library is

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