Library contents

Scala groupMapReduce

groupMapReduce groups items by key, maps each item to a value, and combines the values for each key.

A simple example

groupMapReduce

  1. Start with A has 1, A has 2, B has 4
  2. Do this Sum values for each key
  3. Result A = 3, B = 4
The A values combine into one subtotal. B contributes to its own group.

Syntax

Scala syntax
rows.groupMapReduce(key)(value)(combine)
Run this example in Scala

Save the program as Lesson.scala. Use Scala 2.13.

scalac Lesson.scala
scala Lesson

Total item quantities by warehouse

A team receives a batch of readings or transactions and wants a compact report. Aggregate the records by the requested grouping so the result can be checked against the individual inputs.

From the programprintln(s"$key=" + totals.getOrElse(key, 0))
First output lineeast=7
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
    val rows = List(("east", 3), ("west", 1), ("east", 4))
    val totals = rows.groupMapReduce(_._1)(_._2)(_ + _)
    for (key <- List("east", "west", "north")) {
      println(s"$key=" + totals.getOrElse(key, 0))
    }
  }
}
Output
east=7
west=1
north=0

Addition works as the reducer for quantities. An absent warehouse has no map entry, so getOrElse supplies zero when displaying a fixed list of warehouses.

Scala documentation for groupMapReduce

Advertisements

Total studio deliveries

A store records three boxes of supplies against their destination studios. Group the quantities by location and add the values within each group. What total belongs to the named location?

GivenArt 4 · Lab 8 · Art 3 | Art total
Worked result7

Total tickets by door

The front desk receives two west-door reports and an east-door report. Group the quantities by location and add the values within each group. What total belongs to the named location?

GivenW 6 · E 9 · W 4 | W total
Worked result10