Skip to content

Instantly share code, notes, and snippets.

@davidandrzej
Last active December 16, 2015 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidandrzej/5413350 to your computer and use it in GitHub Desktop.
Save davidandrzej/5413350 to your computer and use it in GitHub Desktop.
Combining two Map[String,Int] with key-wise addition.
object CombineMaps {
type Counts = Map[String,Int]
def combine(x: Counts, y: Counts): Counts = {
val x0 = x.withDefaultValue(0)
val y0 = y.withDefaultValue(0)
val keys = x.keys.toSet.union(y.keys.toSet)
keys.map{ k => (k -> (x0(k) + y0(k))) }.toMap
}
}
val counts1 = Map("boats" -> 1, "against" -> 2,
"the" -> 10, "current" -> 1)
val counts2 = Map("burned" -> 1, "the" -> 5, "boats" -> 1)
println(CombineMaps.combine(counts1,counts2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment