Search code examples
scaladictionarymergehashmap

scala merge two maps Map[String, Long] fastest approach


I want to merge two maps in fastest possible way by grouping by key and returning sum of values

val m1: Map[String, Long]
val m2: Map[String, Long]

currently, I do:

(m1.toSeq ++ m2.toSeq).groupBy(_._1).mapValues(_.map(_._2).sum)

What's faster approach? Would HashMap be faster?


Solution

  • val m3 = m1.foldLeft(m2) { case (accMap, (key, value)) =>
      val accValue = accMap.getOrElse(key, 0)
      accMap + (key -> (value + accValue))
    }