Scala — Counting values with groupMapReduce
Scala groupMapReduce groups elements by key and combines each group’s mapped values. Mapping each observation to one and summing gives a frequency count.
A simple example
Look up one count
- Start with Key A has value 2
- Do this Look up A
- Result 2
object Lesson extends App {
val counts = Map("A" -> 2)
println(counts("A"))
}
2
Count labels without relying on storage order
groupMapReduce groups by each string, assigns one per observation, and sums within groups. It is available in Scala 2.13 and Scala 3 collections. The second list controls display order.
A volunteer scans a red wristband, a blue one, then another red one. Increase the count for that colour on each scan. Look up red and blue by name when printing the totals.
Run the example
Scala 2.13 with JDK 11 or later. Run these commands from the directory containing the example.
scalac Lesson.scala
scala Lesson
object Lesson {
def main(args: Array[String]): Unit = {
val colors = List("red", "blue", "red")
val counts = colors.groupMapReduce(identity)(_ => 1)(_ + _)
for (color <- List("red", "blue")) {
println(color + " " + counts(color))
}
}
}
red 2 blue 1
The first red contributes one count, blue contributes one, and the second red brings its count to two. Reading the red and blue keys in a specified order makes the report reproducible.
Try it yourself
Insert another blue before the last red. What changes?
Check your answer
Both keys now have a count of two. The requested display order stays red, then blue.