Scala Map: Sort by values in ascending order
Scala Map Exercise-17 with Solution
Write a Scala program to create a map and sort it by values in ascending order.
Sample Solution:
Scala Code:
object SortMapByValuesExample {
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 values in ascending order
val sortedMap = color_map.toSeq.sortBy(_._2).toMap
// Print the sorted map
println("Sorted map by values:")
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 values: Key: Red, Value: 1 Key: Blue, Value: 2 Key: Orange, Value: 3 Key: Green, Value: 4
Explanation:
In the above exercise,
In this program, we create a map "color_map" using the Map constructor and provide key-value pairs.
Following are the steps to sort the map by values in ascending order:
- Convert the map to a sequence of key-value pairs using the toSeq method.
- Use the sortBy method on the sequence and specify .2 as the sorting criterion, which refers to the second element of each pair (the value).
- Convert the sorted sequence back to a map using the toMap method.
In the end, we display each key-value pair by iterating over the sorted map using println.
Scala Code Editor :
Previous: Sort by keys in ascending order.
Next: Find common keys between two maps.
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://w3resource.com/scala-exercises/map/scala-map-exercise-17.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics