Lesson contents

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

  1. Start with Key A has value 2
  2. Do this Look up A
  3. Result 2
The key identifies which stored value to read.
Lesson.scala
object Lesson extends App {
    val counts = Map("A" -> 2)
    println(counts("A"))
}
Output
2
Advertisements

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.

Scan order: Red, blue, red. Red team: 2 wristbands. Blue team: 1 wristband.
Count team wristbands

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
Lesson.scala
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))
    }
  }
}
Output
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.

Tour of Scala

Related tags

  • Scala
  • collections
  • frequency counts
  • lookup