Sorting is comparing. A List
contains numbers, like 30, 20, 50. To sort them, we must compare them against each other. An ordering is imposed.
With Scala 3.3, we use the sorted function. A List
is immutable, so sorted returns a sorted copy of the list. With the Ordering class
, we access common sort types.
Let us begin. Here we invoke the sorted function. With no arguments, this returns a List
containing the same elements, but sorted in ascending order (from low to high).
Ordering.Int.reverse
to supply "sorted" with an Ordering argument. This affects the sort order (to be descending).object Program { def main(args: Array[String]): Unit = { // An example list. val positions = List(300, 20, 10, 300, 30) // Sort Ints from low to high (ascending). val result = positions.sorted println(result) // Sort Ints in reverse order (from high to low, descending). val result2 = positions.sorted(Ordering.Int.reverse) println(result2) // The original list is unchanged. println(positions) } }List(10, 20, 30, 300, 300) List(300, 300, 30, 20, 10) List(300, 20, 10, 300, 30)
SortWith
To use this function, we must pass another function (called "lt"). The argument function, specified as a lambda, must return true if the first argument is less than the second.
List
of strings by their lengths. To come first, a string
must have a smaller length (shortest are first).object Program { def main(args: Array[String]): Unit = { // Contains 4 strings of different lengths. val codes = List("abc", "defg", "hi", "jklmn") // Sort list by lengths of strings. val result = codes.sortWith((x, y) => x.length() < y.length()) // Print all strings in sorted list. result.foreach(println(_)) } }hi abc defg jklmn
SortBy
With this function, we specify a lambda to create a special sorting key (like a tuple). Here we build a two-element tuple based on each string
in the list.
char
(at index 1) before the first char
(at index 0). So the following digit is the primary sort.object Program { def main(args: Array[String]): Unit = { // These ids all have a start char and an ending digit. val ids = List("a5", "b0", "z0", "c9", "d9", "d0", "d5") // Use sortBy. // ... Create a sort key. // The second char is first. // And the first char second. val result = ids.sortBy((x: String) => (x.charAt(1), x.charAt(0))) // Print our sorted ids. result.foreach(println(_)) } }b0 d0 z0 a5 d5 c9 d9
In Scala we do not sort Lists in-place. They are immutable. But we use lambda expressions, and the Ordering type, to create sorted copies of these lists.