Projects & Stories

Scala: Sum up values in a Map

Some addition to my previous code snippet post.

scala> val m = Map("k1" -> 1.6, "k2" -> 2.2)
m: scala.collection.immutable.Map[java.lang.String,Double] = Map(k1 -> 1.6, k2 -> 2.2)

scala> m.foldLeft(0.0){ case (a, (k, v)) => a + v }
res16: Double = 3.8000000000000003

Instead of pattern matching you can also use the underscore solution:

scala> m.foldLeft(0.0)(_+_._2)
res40: Double = 3.8000000000000003

The parameter you pass to foldLeft, in this example 0.0, will be add up with _._2 which stands for the second element in the Map.

Documentation scheme:

foldLeft[B](z: B)(op: (B, (A, B)) ⇒ B): B

It took me a while to understand the underscore-black-magic from Scala, but in the end (as a one-line-lover) I really like it :)