Scala Sorted List Examples: Ordering.IntUse sorted, and Ordering, to sort an Int list in ascending and descending order.
Sorted. 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, 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: 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
// Sort Ints in reverse order (from high to low, descending).
val result2 = positions.sorted(Ordering.Int.reverse)
// The original list is unchanged.
List(10, 20, 30, 300, 300)
List(300, 300, 30, 20, 10)
List(300, 20, 10, 300, 30)
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.
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.
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.Tuple
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.
A review. 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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.