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 :
mapName.toSeq.sortBy(_._1):_*
Let’s try to understand it with better example.
Example #1:
import scala.collection.immutable.ListMap
object GfG
{
def main(args : Array[String])
{
val mapIm = Map( "Zash" - > 30 ,
"Jhavesh" - > 20 ,
"Charlie" - > 50 )
val res = ListMap(mapIm.toSeq.sortBy( _ . _ 1 ) :_ *)
println(res)
}
}
|
Output:
Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)
Example #2:
import scala.collection.immutable.ListMap
object GfG
{
def main(args : Array[String])
{
val mapIm = Map( "Zash" - > 30 ,
"Jhavesh" - > 20 ,
"Charlie" - > 50 )
val res = ListMap(mapIm.toSeq.sortWith( _ . _ 1 < _ . _ 1 ) :_ *)
println(res)
}
}
|
Output:
Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)
Example #3:
import scala.collection.immutable.ListMap
object GfG
{
def main(args : Array[String])
{
val mapIm = Map( "Zash" - > 30 ,
"Jhavesh" - > 20 ,
"Charlie" - > 50 )
val res = ListMap(mapIm.toSeq.sortWith( _ . _ 1 > _ . _ 1 ) :_ *)
println(res)
}
}
|
Output:
Map(Zash -> 30, Jhavesh -> 20, Charlie -> 50)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
13 Aug, 2019
Like Article
Save Article