C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Ordering.Int: We use Ordering.Int.reverse to supply "sorted" with an Ordering argument. This affects the sort order (to be descending).
Scala program that sorts List
// 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)
Output
List(10, 20, 30, 300, 300)
List(300, 300, 30, 20, 10)
List(300, 20, 10, 300, 30)
Here: We sort a List of strings by their lengths. To come first, a string must have a smaller length (shortest are first).
Scala program that uses sortWith
// Contains four 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(_))
Output
hi
abc
defg
jklmn
Note: Our sort key uses the second char (at index 1) before the first char (at index 0). So the following digit is the primary sort.
Tip: Any transformation function that yields something that can be sorted (that has an Ordering) can be used.
Scala program that uses sortBy
// 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(_))
Output
b0
d0
z0
a5
d5
c9
d9