Groovy — Counting keys with countBy
In Groovy, countBy calls a closure for each element and counts how often each returned key appears. Returning each label itself gives one count per distinct label.
A simple example
Look up one count
- Start with Key A has value 2
- Do this Look up A
- Result 2
def counts = [A: 2]
println(counts.A)
2
Count labels without relying on storage order
countBy calls a closure for every list element and increments the count for the key it returns. Returning the color itself groups identical strings together.
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
Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
def counts = ['red', 'blue', 'red'].countBy { color -> color }
['red', 'blue'].each { color ->
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.