w3resource

Scala Map: Find keys with maximum value

Scala Map Exercise-14 with Solution

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

Sample Solution:

Scala Code:

object FindKeysWithMaximumValueExample {
  def main(args: Array[String]): Unit = {
    // Create a map
    var color_map = Map("Red" -> 1, "Green" -> 4, "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

    // Find the keys with the maximum value
    val keysWithMaxValue = color_map.filter(_._2 == maxValue).keys

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

Sample Output:

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

Explanation:

In the above exercise,

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

In order to find the keys with the maximum value in the map, we follow these steps:

  • Find the maximum value in the map using the values.max method.
  • To filter key-value pairs where the value is equal to the maximum, use the filter method on the map.
  • Using the keys method, retrieve the keys from filtered key-value pairs.

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

Scala Code Editor :

Previous: Find average of values.
Next: Find keys with minimum value.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.