w3resource

Scala Map: Find average of values

Scala Map Exercise-13 with Solution

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

Sample Solution:

Scala Code:

object FindAverageOfValuesInMapExample {
  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 average of all values in the map
    val values = color_map.values
    val sum = values.sum
    val average = sum.toDouble / values.size

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

Sample Output:

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

Explanation:

In the above exercise,

First, we create a map "color_map" using the Map constructor and provide key-value pairs.

Following are the steps to find the average of all values on the map:

  • Retrieve the map's values collection using the values method.
  • Calculate the sum of all values using the sum method.
  • Convert the sum to Double and divide it by the collection size to obtain the average.

Finally, we print the result using println, including the average of all values.

Scala Code Editor :

Previous: Calculate sum of values.
Next: Find keys with maximum value.

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://www.w3resource.com/scala-exercises/map/scala-map-exercise-13.php