Scala Map: Find maximum value
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics