w3resource

Scala Map: Find the minimum value

Scala Map Exercise-10 with Solution

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

Sample Solution:

Scala Code:

object FindMinimumValueInMapExample {
  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 minimum value in the map
    val minValue = color_map.values.min

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

Sample Output:

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

Explanation:

In the above exercise,

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

Scala Code Editor :

Previous: Validate value presence in a map.
Next: Find maximum value.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.