w3resource

Scala Map: Calculate sum of values

Scala Map Exercise-12 with Solution

Write a Scala program to create a map and find the sum of all values in the map.

Sample Solution:

Scala Code:

object FindSumOfValuesInMapExample {
  def main(args: Array[String]): Unit = {
    // Create a map
    var color_map = Map("Red" -> 1, "Green" -> 2, "Blue" -> 3, "Orange" -> 4)
   
    // Print the original map
    println("Original map: " + color_map)

    // Find the sum of all values in the map
    val sum = color_map.values.sum

    // Print the result
    println(s"The sum of all values in the map is: $sum")
  }
}

Sample Output:

Original map: Map(Red -> 1, Green -> 2, Blue -> 3, Orange -> 4)
The sum of all values in the map is: 10

Explanation:

In the above exercise,

  • First, we create a map "color_map" using the Map constructor and provide key-value pairs.
  • To find the sum of all values in the map, we use the values method to obtain a collection of all the values in the map. Then, we use the sum method on the collection to calculate the sum of all values.
  • Finally, we print the result using println, including the sum of all values.

Scala Code Editor :

Previous: Find maximum value.
Next: Find average of values.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/map/scala-map-exercise-12.php