Grouping and Sorting
groupBy and sortBy.
Organizing data
Real-world data often needs to be grouped by a property or sorted by a key. Scala collections offer groupBy, sortBy, sortWith, and friends to do this declaratively.
object Main {
def main(args: Array[String]): Unit = {
val nums = List(5, 3, 8, 1, 9, 2)
println(nums.sorted)
}
}sorted: natural order
sorted sorts elements in their natural order (ascending for numbers, alphabetical for strings). It needs an ordering, which exists for common types.
object Main {
def main(args: Array[String]): Unit = {
println(List(3, 1, 2).sorted)
println(List("pear", "apple", "fig").sorted)
}
}All lessons in this course
- List, Vector, Set, Map
- Transformations
- Folding and Reducing
- Grouping and Sorting