Scala collections can be sorted with .sorted. This returns a sorted collection in ascending order.
val numbers = List(5, 2, 11, 7, 3)
val sortedNumbers = numbers.sorted
// sortedNumbers is List(2, 3, 5, 7, 11)
To sort in descending order, use .sorted.reverse:
val descending = numbers.sorted.reverse
For custom ordering, use sortWith:
val words = List("pie", "banana", "book")
val byLength = words.sortWith((a, b) => a.length < b.length)
Sorting takes O(n log n) time for typical collections.
Assignment
Follow the Coding Tutorial and sort the collection.
Hint
Use .sorted for ascending order.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check