w3resource

Scala Map: Find keys with minimum value

Scala Map Exercise-15 with Solution

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

Sample Solution:

Scala Code:

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

   // Find the minimum value in the map
    val minValue = color_map.values.min

    // Find the keys with the minimum value
    val keysWithMinValue = color_map.filter(_._2 == minValue).keys

    // Print the result
    println(s"The keys with the minimum value are: $keysWithMinValue")
  }
}

Sample Output:

Original map: Map(Red -> 1, Green -> 4, Blue -> 1, Orange -> 4)
The keys with the minimum value are: Set(Red, Blue)

Explanation:

In the above exercise,

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

We follow these steps to find the keys in the map with the minimum value:

  • Find the minimum value in the map using the values.min method.
  • Apply the filter method to the map to filter key-value pairs with a value equal to the minimum.
  • Using the keys method, retrieve the keys from filtered key-value pairs.

Finally, we print the result using println, including the keys with the minimum value.

Scala Code Editor :

Previous: Find keys with maximum value.
Next: Sort by keys in ascending order.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.