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
- Start with Two entries for A, first 1 then 2
- Do this Build an index keyed by A
- Result A has 2
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.
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()
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
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?
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?