Library contents

Groovy collectEntries

collectEntries transforms each input record into an entry and collects the entries in a map. Later entries replace earlier values for the same key.

A simple example

collectEntries

  1. Start with Two entries for A, first 1 then 2
  2. Do this Build an index keyed by A
  3. Result A has 2
The second entry uses the same key and supplies the value that remains in the new map.

Syntax

Groovy syntax
rows.collectEntries { row -> [(row.id): row.value] }
Run this example in Groovy

Save the program as Lesson.groovy. Use Groovy 4 on the JVM.

groovy Lesson.groovy

Build a lookup map with a duplicate-key rule

An export contains keys that may identify more than one input record. Establish what happens at a repeated key before constructing the lookup so useful records are not discarded unintentionally.

First output linerevised
Lesson.groovy
def rows = [[id: 7, value: 'draft'], [id: 8, value: 'ready'], [id: 7, value: 'revised']]
def latest = rows.collectEntries { row -> [(row.id): row.value] }
println latest[7]
println rows.groupBy { it.id }[7].size()
Output
revised
2

A lookup map can retain only one value per key. Comparing it with groupBy exposes how many source records contributed to that key.

Groovy documentation for collectEntries

Advertisements

Replace a room’s contact

A caretaker imports an older duty roster followed by the current roster. Build the lookup in the supplied order. A later record with the same key replaces the earlier value. Which value is returned for that key?

GivenA → Ivo · B → Ada · A → Rae
Worked resultRae

Update an exhibit assignment

A gallery reassigns its only audio guide during the morning. Build the lookup in the supplied order. A later record with the same key replaces the earlier value. Which value is returned for that key?

GivenG1 → West · G1 → East
Worked resultEast