Open In App

How to Use Sortby in Scala?

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  1. In this approach, we are using the sortBy function in Scala to sort an array of integers in ascending order.
  2. The lambda function x => x is used as the sorting criteria, where x represents each element in the array.
  3. 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:

Screenshot-2024-03-29-at-14-58-56-Scastie---An-interactive-playground-for-Scala

Using SortBy for Sorting an Array in Reverse Order

  1. 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).
  2. The lambda function x => -x is used as the sorting criteria, where x represents each element in the array.
  3. 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:

Screenshot-2024-03-29-at-14-59-38-Scastie---An-interactive-playground-for-Scala

Using SortBy for Sorting By the Second Attribute

  1. In this approach, we are using the sortBy function in Scala to sort a list of tuples by the second attribute (age).
  2. The lambda function _._2 is used as the sorting criteria, where _._2 represents the second element of each tuple in the list.
  3. 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:

Screenshot-2024-03-29-at-15-00-37-Scastie---An-interactive-playground-for-Scala

Using SortBy for Sorting a Map Value

  1. In this approach, we are using the sortBy function in Scala to sort a map by its values (ages).
  2. 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.
  3. Next, we convert the sorted sequence back into a ListMap to preserve the sorted order by values.
  4. 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:

Screenshot-2024-03-29-at-15-01-35-Scastie---An-interactive-playground-for-Scala



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads