groupBy, sorting and splitting
A program that has collected its data usually ends by arranging it: which elements belong together, in which order they are read, and which one is the smallest or the largest. groupBy answers the first, sortBy and sortWith the second, minBy and maxBy the third, and partition and span split a collection in two without sorting it.
Grouping by a key
groupBy turns a collection into a map from the key to the list of elements that share it. groupMap does the same and maps each element on the way in, and groupMapReduce reduces each group as it is built:
grouping.scala
case class Person(name: String, age: Int, city: String)
val people = List(
Person("Ada", 36, "London"),
Person("Grace", 45, "New York"),
Person("Alan", 41, "London"),
Person("Edsger", 72, "Austin")
)
@main def grouping(): Unit =
val byCity = people.groupBy(_.city)
byCity.toList.sortBy(_._1).foreach { (city, group) =>
println(s"$city: ${group.map(_.name).sorted.mkString(", ")}")
}
println(people.groupMap(_.city)(_.name).toList.sortBy(_._1))
println(people.groupMapReduce(_.city)(_ => 1)(_ + _).toList.sortBy(_._1))
val (senior, junior) = people.partition(_.age >= 45)
println(senior.map(_.name).sorted)
println(junior.map(_.name).sorted)
val (young, rest) = people.span(_.age < 45)
println(young.map(_.name))
println(rest.map(_.name))
scala-cli run --server=false grouping.scala
Austin: Edsger
London: Ada, Alan
New York: Grace
List((Austin,List(Edsger)), (London,List(Ada, Alan)), (New York,List(Grace)))
List((Austin,1), (London,2), (New York,1))
List(Edsger, Grace)
List(Ada, Alan)
List(Ada)
List(Grace, Alan, Edsger)
The map a grouping produces has no order, so the program sorts its entries before printing them and sorts the names inside each group. partition splits by a condition and keeps the order, which is why the second list is List(Ada, Alan); span stops at the first element that fails and does not look further, so the two halves follow the order of the input.
Sorting and picking one
sortBy takes a key and sorts by it, sortWith takes a comparison, and a tuple as the key sorts by the first field and then by the second. minBy and maxBy find one element by the same kind of key:
sorting.scala
case class Person(name: String, age: Int, city: String)
val people = List(
Person("Ada", 36, "London"),
Person("Grace", 45, "New York"),
Person("Alan", 41, "London"),
Person("Edsger", 72, "Austin")
)
@main def sorting(): Unit =
println(people.sortBy(_.age).map(_.name))
println(people.sortBy(person => (-person.age, person.name)).map(_.name))
println(people.sortWith((a, b) => a.name < b.name).map(_.name))
println(people.minBy(_.age).name)
println(people.maxBy(_.age).name)
println(people.map(_.city).sorted)
println(people.sortBy(_.city).map(person => s"${person.name} (${person.city})"))
scala-cli run --server=false sorting.scala
List(Ada, Alan, Grace, Edsger)
List(Edsger, Grace, Alan, Ada)
List(Ada, Alan, Edsger, Grace)
Ada
Edsger
List(Austin, London, London, New York)
List(Edsger (Austin), Ada (London), Alan (London), Grace (New York))
sortBy(person => (-person.age, person.name)) sorts by age descending and then by name, because a negative key reverses the first field only. The sort is stable, so elements with equal keys keep their relative order, which is what makes a two-field key unnecessary where the input already has an order. Sorting a list of strings uses the lexicographic order of String, and Ordering is an ordinary given instance that a program can supply its own of.
Related
- map, flatMap, filter and fold: the transformations this lesson ends a pipeline with.
- Sets and maps: the map a grouping returns.
- Type classes: the Ordering a sort reads, in a later part.
- Case classes: the record a sort key is read from.
Article author: Arthur Isaev