How to use the sorted Method In Scala
Scala’s sorted method allows you to sort a list of elements in ascending order. This method returns a new sorted list without modifying the original list.
object Main {
def main(args: Array[String]): Unit = {
val numbers = List(5, 3, 8, 1, 2, 4, 7, 6)
val sortedNumbers = numbers.sorted
println(numbers)
println(sortedNumbers) // Output: List(1, 2, 3, 4, 5, 6, 7, 8)
}
}
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:
- Sorting in Descending Order: