Map is same as dictionary which holds key:value pairs. In this article, we will learn how to sort a Scala Map by key. We can sort the map by key, from low to high or high to low, using sortBy.
Syntax :
Scala
Scala
Scala
mapName.toSeq.sortBy(_._1):_*Let's try to understand it with better example. Example #1:
// Scala program to sort given map by key
import scala.collection.immutable.ListMap
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a map
val mapIm = Map("Zash" -> 30,
"Jhavesh" -> 20,
"Charlie" -> 50)
// Sort map by key
val res = ListMap(mapIm.toSeq.sortBy(_._1):_*)
println(res)
}
}
Output:
Example #2:
Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)
// Scala program to sort given map by key
import scala.collection.immutable.ListMap
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a map
val mapIm = Map("Zash" -> 30,
"Jhavesh" -> 20,
"Charlie" -> 50)
// reverse map in ascending order
val res = ListMap(mapIm.toSeq.sortWith(_._1 < _._1):_*)
println(res)
}
}
Output:
Example #3:
Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)
// Scala program to sort given map by key
import scala.collection.immutable.ListMap
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a map
val mapIm = Map("Zash" -> 30,
"Jhavesh" -> 20,
"Charlie" -> 50)
// reverse map in descending order
val res = ListMap(mapIm.toSeq.sortWith(_._1 > _._1):_*)
println(res)
}
}
Output:
Map(Zash -> 30, Jhavesh -> 20, Charlie -> 50)