How to use SortBy for Sorting an Array In Scala
- 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.
// 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:
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.