How to Use Sortby in Scala?
Last Updated :
08 Apr, 2024
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.
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.
Using SortBy for Sorting an Array
- In this approach, we are using the sortBy function in Scala to sort an array of integers in ascending order.
- The lambda function x => x is used as the sorting criteria, where x represents each element in the array.
- This method sorts the array and prints the sorted numbers using foreach(println).
In the below example, the sortBy is used to sort an array.
Scala
// Creating Object
object GFG {
// Main Method
def main(args: Array[String]): Unit = {
// Creating an array of integers
val numbers = Array(5, 3, 9, 1, 7)
// Sorting the array in ascending order using sortBy
val sortedNumbers = numbers.sortBy(x => x)
// Printing the sorted array
println("Sorted Numbers:")
sortedNumbers.foreach(println)
}
}
Output:

Using SortBy for Sorting an Array in Reverse Order
- In this approach, we are using the sortBy function in Scala with a custom comparator -x to sort an array of integers in reverse order (descending).
- The lambda function x => -x is used as the sorting criteria, where x represents each element in the array.
- This method sorts the array in reverse order and prints the sorted numbers in reverse order using foreach(println).
In the below example, the sortBy is used to sort an array in reverse order.
Scala
// Creating Object
object GFG {
// Main Method
def main(args: Array[String]): Unit = {
// Creating an array of integers
val numbers = Array(5, 3, 9, 1, 7)
// Sorting the array in reverse order using sortBy with a custom comparator
val sortedNumbers = numbers.sortBy(x => -x)
// Printing the sorted array
println("Sorted Numbers (Reverse Order):")
sortedNumbers.foreach(println)
}
}
Output:

Using SortBy for Sorting By the Second Attribute
- In this approach, we are using the sortBy function in Scala to sort a list of tuples by the second attribute (age).
- The lambda function _._2 is used as the sorting criteria, where _._2 represents the second element of each tuple in the list.
- This method sorts the list by age and prints the sorted list of people by their ages using foreach(println).
In the below example, the sortBy is used for sorting by the second attribute.
Scala
// Creating Object
object GFG {
// Main Method
def main(args: Array[String]): Unit = {
// Creating a list of tuples (name, age)
val people = List(("GFG1", 25), ("GFG2", 30), ("GFG3", 20), ("GFG4", 35))
// Sorting the list of tuples by the second attribute (age)
val sortedPeople = people.sortBy(_._2)
// Printing the sorted list
println("Sorted People (By Age):")
sortedPeople.foreach(println)
}
}
Output:

Using SortBy for Sorting a Map Value
- 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.
Scala
// 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:

Similar Reads
How to Sort a list in Scala? Sorting a list is a common operation in programming, and Scala provides convenient ways to accomplish this task. In this article, we'll explore different methods to sort a list in Scala, along with examples. Table of Content Using the sorted Method:Using the sortBy Method:Using the sortWith Method:S
2 min read
How to Sort an Array in Scala? Sorting arrays effectively is essential for many applications, regardless of whether you're working with texts, custom objects, or numerical data. Because Scala is a strong and expressive language, it provides a variety of array sorting methods that may be customized to fit various needs and situati
5 min read
How to sort a Scala Map by value 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 // Scala program to sort given map by value impor
2 min read
How to sort by value in PySpark? In this article, we are going to sort by value in PySpark.Creating RDD for demonstration:Pythonfrom pyspark.sql import SparkSession, Row # creating sparksession and giving an app name spark = SparkSession.builder.appName('sparkdf').getOrCreate() # create 2 Rows with 3 columns data = Row(First_name="
2 min read
How to use java library in Scala? As Scala and Java are meant to work together effortlessly, using Java libraries in Scala programming is a breeze. To utilize a Java library in Scala, follow these steps: Importing Java Classes: Use Scala's import statement to import the required Java classes or packages.Creating Java Objects: Use Sc
2 min read