Scala sum Map values
casting, dictionary, scala
Solution
You can use foldLeft function:
scala> val l : List[Map[String,Any]] = List(Map("a" -> 1, "b" -> 2.8), Map("a" -> 3, "c" -> 4), Map("c" -> 5, "d" -> "abc"))
l: List[Map[String,Any]] = List(Map(a -> 1, b -> 2.8), Map(a -> 3, c -> 4), Map(c -> 5, d -> abc))
scala> val (sa, sb, sc) = l.foldLeft((0: Int, 0: Double, 0: Int)){
| case ((a, b, c), m) => (
| a + m.get("a").collect{case i: Int => i}.getOrElse(0),
| b + m.get("b").collect{case i: Double => i}.getOrElse(0.),
| c + m.get("c").collect{case i: Int => i}.getOrElse(0)
| )
| }
sa: Int = 4
sb: Double = 2.8
sc: Int = 9
Updated using incrop's idea of `collect` instead of `match`.
Problem
I have a List ``` val l : List[Map[String,Any]] = List(Map("a" -> 1, "b" -> 2.8), Map("a" -> 3, "c" -> 4), Map("c" -> 5, "d" -> "abc")) ``` and I used the following code to find the sum for the keys "a" (Int), "b" (Double) and "c" (Int). "d" is included as noise. ``` l.map(n => n.mapValues( v => if (v.isInstanceOf[Number]) {v match { case x:Int => x.asInstanceOf[Int] case x:Double => x.asInstanceOf[Double] }} else 0)).foldLeft((0,0.0,0))((t, m) => ( t._1 + m.get("a").getOrElse(0), t._2 + m.get("b").getOrElse(0.0), t._3 + m.get("c").getOrElse(0))) ``` I expect the output would be (4, 2.8, 9) but instead I was trashed with ``` <console>:10: error: overloaded method value + with alternatives: (x: Int)Int <and> (x: Char)Int <and> (x: Short)Int <and> (x: Byte)Int cannot be applied to (AnyVal) ``` I think the exception was trying to tell me that '+' doesn't work with AnyVal. How do I get this to work to get my the result that I want? Thanks