VOOZH about

URL: https://www.geeksforgeeks.org/scala/how-to-sort-a-scala-map-by-key/

⇱ How to sort a Scala Map by key - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to sort a Scala Map by key

Last Updated : 13 Aug, 2019
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:
Output:
Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)
Example #2:
Output:
Map(Charlie -> 50, Jhavesh -> 20, Zash -> 30)
Example #3:
Output:
Map(Zash -> 30, Jhavesh -> 20, Charlie -> 50)
Comment
Article Tags:

Explore