Scala Map: Sort by keys in ascending order
Scala Map Exercise-16 with Solution
Write a Scala program to create a map and sort it by keys in ascending order.
Sample Solution:
Scala Code:
object SortMapByKeysExample {
def main(args: Array[String]): Unit = {
// Create a map
var color_map = Map("Red" -> 1, "Green" -> 4, "Blue" -> 2, "Orange" -> 3)
// Print the original map
println("Original map: " + color_map)
// Sort the map by keys in ascending order
val sortedMap = color_map.toSeq.sortBy(_._1).toMap
// Print the sorted map
println("Sorted map by keys:")
sortedMap.foreach { case (key, value) =>
println(s"Key: $key, Value: $value")
}
}
}
Sample Output:
Original map: Map(Red -> 1, Green -> 4, Blue -> 2, Orange -> 3) Sorted map by keys: Key: Blue, Value: 2 Key: Green, Value: 4 Key: Orange, Value: 3 Key: Red, Value: 1
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 in the map with the minimum value, we follow these steps:
- 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 results using println, including the minimum valued keys.
Scala Code Editor :
Previous: Find keys with minimum value.
Next: Sort by values in ascending order.
What is the difficulty level of this exercise?
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-16.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics