In this article, we will learn how to sort a Scala Map by value. We can sort the map by key, from low to high or high to low, using sortBy method.
Syntax:
MapName.toSeq.sortBy(_._2):_*
Let’s try to understand it with better example.
Example #1:
Scala
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( _ . _ 2 ) :_ *)
println(res)
}
}
|
Output: Map(Jhavesh -> 20, Zash -> 30, Charlie -> 50)
In above example, we can see mapIm.toSeq.sortBy method is used to sort the map by key values.
Example #2:
Scala
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( _ . _ 2 < _ . _ 2 ) :_ *)
println(res)
}
}
|
Output: Map(Jhavesh -> 20, Zash -> 30, Charlie -> 50)
Here, In above example we are sorting map in ascending order by using mapIm.toSeq.sortWith(_._2 < _._2):_*
Example #3:
Scala
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( _ . _ 2 > _ . _ 2 ) :_ *)
println(res)
}
}
|
Output: Map(Charlie -> 50, Zash -> 30, Jhavesh -> 20)
Above example show to sorting map in descending order.