Scala Sorting and Ordering
Sorting is arranging items in a chosen order, such as smallest first or alphabetical. An ordering is the rule that decides which item comes first.
Sorted uses the natural order
Numbers sort smallest first, and strings sort alphabetically. Both results are new lists.
@main def main(): Unit =
println(List(3, 1, 2).sorted)
println(List("pear", "apple", "fig").sorted)SortBy sorts by a key you pick
Sorting by name arranges the people alphabetically by their names. The printed list shows only the names, in order.
case class Person(name: String, age: Int)
@main def main(): Unit =
val people = List(Person("bo", 30), Person("ana", 25), Person("cy", 28))
println(people.sortBy(_.name).map(_.name))A given Ordering teaches sorted a custom type
The given ordering compares people by age, so sorted arranges them youngest first. The printed ages prove the order.
case class Person(name: String, age: Int)
given Ordering[Person] = Ordering.by((p: Person) => p.age)
@main def main(): Unit =
val people = List(Person("bo", 30), Person("ana", 25), Person("cy", 28))
println(people.sorted.map(_.age))Example
case class Person(name: String, age: Int)
given Ordering[Person] = Ordering.by((p: Person) => p.age)
@main def main(): Unit =
val people = List(Person("bo", 30), Person("ana", 25), Person("cy", 28))
println(people.sorted.map(_.name))
println(people.sortWith((a, b) => a.age > b.age).map(_.name))Key points
- Sorted: sorted arranges numbers and strings in their natural order.
- SortBy: sortBy arranges items by a key you pick, such as a name.
- SortWith: sortWith arranges items with a comparison you write.
- Ordering: a given Ordering tells sorted how to compare a custom type.
- Reverse: reverse after a sort flips the order to largest first.
In this example, the given ordering sorts the people youngest first, so the first printed list runs from Ana to Bo. The sortWith comparison then flips the rule to oldest first, so the second printed list runs from Bo back to Ana.
Note
sorted returns a new list and leaves the original unchanged.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
You have a list of people and want them sorted by age, youngest first, using sorted. What do you need in scope?