📜  如何按键排序Scala Map

📅  最后修改于: 2022-05-13 01:55:33.238000             🧑  作者: Mango

如何按键排序Scala Map

Map 与包含键:值对的字典相同。在本文中,我们将学习如何按键对 Scala Map 进行排序。我们可以使用sortBy按键对地图进行排序,从低到高或从高到低。
句法 :

mapName.toSeq.sortBy(_._1):_*

让我们尝试用更好的例子来理解它。
示例 #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)
    } 
} 
输出:
Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)

示例 #2:

// 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)
    } 
} 
输出:
Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)

示例#3:

// 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)
    } 
} 
输出:
Map(Zash -> 30, Jhavesh -> 20, Charlie -> 50)