Sorting in Descending Order
To sort a list in descending order, you can use the reverse method after sorting in ascending order.
object Main {
def main(args: Array[String]) {
val numbers = List(5, 3, 8, 1, 2, 4, 7, 6)
val sortedNumbersDesc = numbers.sorted.reverse
println(sortedNumbersDesc) // Output: List(8, 7, 6, 5, 4, 3, 2, 1)
}
}
Conclusion:
Sorting lists in Scala is straightforward, thanks to the built-in methods like sorted, sortBy, and sortWith. These methods provide flexibility in sorting lists based on different criteria and in different orders. By understanding these methods, you can efficiently sort lists in your Scala programs.
With these examples and explanations, you should now have a solid understanding of how to sort lists in Scala. Whether you’re working with numbers, strings, or custom objects, Scala’s rich collection library provides powerful tools for sorting data efficiently.
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:
Contact Us