w3resource

Scala Map: Find maximum value

Scala Map Exercise-11 with Solution

Write a Scala program to create a map and find the maximum value in the map.

Sample Solution:

Scala Code:

object FindMaximumValueInMapExample {
  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 maximum value in the map
    val maxValue = color_map.values.max

    // Print the result
    println(s"The maximum value in the map is: $maxValue")
  }
}

Sample Output:

Original map: Map(Red -> 1, Green -> 2, Blue -> 3, Orange -> 4)
The maximum value in the map is: 4

Explanation:

In the above exercise,

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

Scala Code Editor :

Previous: Find the minimum value.
Next: Calculate sum 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://www.w3resource.com/scala-exercises/map/scala-map-exercise-11.php