Scala Sorted List Examples: Ordering.IntUse sorted, and Ordering, to sort an Int list in ascending and descending order.
dot net perls
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).
// An example list.
Scala program that sorts 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
// 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).
// Contains four strings of different lengths.
Scala program that uses sortWith
val codes = List("abc"
// Sort list by lengths of strings.
val result = codes.sortWith
((x, y) => x.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.
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.
// These ids all have a start char and an ending digit.
Scala program that uses sortBy
val ids = List("a5"
// Use sortBy.
// ... Create a sort key.
// The second char is first.
// And the first char second.
val result = ids.sortBy
((x: String) =>
// 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-2021 sam allen. send bug reports to email@example.com.