Start learning free

LESSON 199 OF 348 · SORTING

Sorting in Scala in Scala

Lesson

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.


STEP 1 OF 6
    Ctrl + Enter to check

    Sorting in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free