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

Time:10-13

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?

CodePudding user response:

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

CodePudding user response:

If you have cats in scope, all you need is this:

import cats.syntax.all._

val combined = m1 | | m2
  • Related