如何按值对 Scala Map 进行排序
在本文中,我们将学习如何按值对 Scala Map 进行排序。我们可以使用sortBy方法按键对地图进行排序,从低到高或从高到低。
句法:
MapName.toSeq.sortBy(_._2):_*
让我们尝试用更好的例子来理解它。
示例 #1:
Scala
// Scala program to sort given map by value
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 the map by value
val res = ListMap(mapIm.toSeq.sortBy(_._2):_*)
println(res)
}
}
Scala
// Scala program to sort given map by value
// in ascending order
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 value in ascending order
val res = ListMap(mapIm.toSeq.sortWith(_._2 < _._2):_*)
println(res)
}
}
Scala
// Scala program to sort given map by value
// in descending order
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 value in descending order
val res = ListMap(mapIm.toSeq.sortWith(_._2 > _._2):_*)
println(res)
}
}
输出:
Map(Jhavesh -> 20, Zash -> 30, Charlie -> 50)
在上面的示例中,我们可以看到 mapIm.toSeq.sortBy 方法用于按键值对映射进行排序。
示例 #2:
斯卡拉
// Scala program to sort given map by value
// in ascending order
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 value in ascending order
val res = ListMap(mapIm.toSeq.sortWith(_._2 < _._2):_*)
println(res)
}
}
输出:
Map(Jhavesh -> 20, Zash -> 30, Charlie -> 50)
在这里,在上面的例子中,我们使用 mapIm.toSeq.sortWith(_._2 < _._2):_* 对 map 进行升序排序
示例#3:
斯卡拉
// Scala program to sort given map by value
// in descending order
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 value in descending order
val res = ListMap(mapIm.toSeq.sortWith(_._2 > _._2):_*)
println(res)
}
}
输出:
Map(Charlie -> 50, Zash -> 30, Jhavesh -> 20)
上面的示例显示按降序排序地图。