How to use SortBy for Sorting a Map Value In Scala
- In this approach, we are using the sortBy function in Scala to sort a map by its values (ages).
- First, we convert the map people into a sequence using people.toSeq, then we use sortBy(_._2) as the sorting criteria, where _._2 represents the values (ages) of each key-value pair in the map.
- Next, we convert the sorted sequence back into a ListMap to preserve the sorted order by values.
- Finally, we print the sorted map of people by their ages using foreach(println), which prints each key-value pair in the sorted map on a new line.
In the below example, the sortBy is used for sorting a map value.
// Importing required libraries
import scala.collection.immutable.ListMap
// Creating Object
object GFG {
// Main Method
def main(args: Array[String]): Unit = {
// Creating a map of key-value pairs (name -> age)
val people = Map("GFG1" -> 25, "GFG2" -> 30, "GFG3" -> 20, "GFG4" -> 35)
// Sorting the map by values in ascending order using sortBy
val sortedPeople = ListMap(people.toSeq.sortBy(_._2):_*)
// Printing the sorted map
println("Sorted People (By Age):")
sortedPeople.foreach { case (name, age) =>
println(s"$name -> $age")
}
}
}
Output:
How to Use Sortby in Scala?
In this article, we will learn to use the sortBy function in Scala. The sortBy function is used to sort elements in a collection based on specified sorting criteria.
Table of Content
- Using SortBy for Sorting an Array
- Using SortBy for Sorting an Array in Reverse Order
- Using SortBy for Sorting By the Second Attribute
- Using SortBy for Sorting a Map Value
Syntax:
collection.sortBy(function)
Here,
collection: The collection (such as an array, list, map, etc.) that you want to sort.
function: A function that defines the sorting criteria. This function takes an element from the collection and returns the value by which the elements should be sorted.