0

I want to add all the values in a map without using var or any mutable structures. I have tried to do something like this but it doens't work:

val mymap = ("a" -> 1, "b" -> 2) val sum_of_alcohol_consumption = for ((k,v) <- mymap ) yield (sum_of_alcohol_consumption += v) 

I have been told that I can use .sum on a list Please help

Thanks

1
  • Your Map is not a Map, is that an accident? Commented Nov 16, 2017 at 15:54

3 Answers 3

4

You can use the .values function of a Map to return an Iterable List of its values (all of the Integers) and then call the .sum function on that:

val myMap = Map("a" -> 1, "b" -> 2) val sum = myMap.values.sum println(sum) // Outputs: 3 
Sign up to request clarification or add additional context in comments.

Comments

1

An equivalent answer to the more elegant use of sum is to use a fold operation. sum is implemented in a manner similar to this:

val myMap = Map("a" -> 1, "b" -> 2) val sumAlcoholConsumption = myMap.values.foldLeft(0)(_ + _) 

values returns a sequence of only the values in the map. The first foldLeft argument is the zero value (think of it as the initial value for an accumulator value) for the operation. The second argument is a function that adds the current value of the accumulator to the current element, returning the sum of the two values - and it is applied to each value in turn. That said, sum is a lot more convenient.

Comments

0

To get the only values of map, it provides a function values which will return iterable,we can directly appy sum function to it.

scala> val mymap = Map("a" -> 1, "b" -> 2) mymap: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2) scala> mymap.values.sum res7: Int = 3 

Comments