0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

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

  1. List, Vector, Set, Map
  2. Transformations
  3. Folding and Reducing
  4. Grouping and Sorting
← Back to Scala for Backend Engineering & Functional Programming