ext2008
ext2008

Reputation: 9

How to use reduce to sum lists in a map

I have generated a map in the following type

immutable.Map[Int,List[Double]]

Map(
1 -> List(1.02),
2 -> List(0.42, 6.88))

I'm having trouble understanding how to access the List() in my map and use reduce to sum the elements.

myMap.reduce(???)

Upvotes: 0

Views: 94

Answers (1)

Tyler
Tyler

Reputation: 18187

You can iterate a Map using the .map() function. Each iteration you will get a key and value, and you need to return a key and a value. In your case the key will be one of your Integers (1, 2) and we can just pass that straight through. The value will be a List of Doubles, which we can sum using the built in .sum:

myMap.map { case (key, value) => (key, value.sum) } 

Example:

scala> val myMap = Map(1 -> List(1.02), 2 -> List(0.42, 6.88))
myMap: scala.collection.immutable.Map[Int,List[Double]] = Map(1 -> List(1.02), 2 -> List(0.42, 6.88))

scala> myMap.map { case (key, value) => (key, value.sum) } 
res0: scala.collection.immutable.Map[Int,Double] = Map(1 -> 1.02, 2 -> 7.3)

You can replace .sum with .reduce(_ + _) and get the same answer.

Upvotes: 4

Related Questions