Groovy countBy
countBy applies a closure to each input and returns a map of key frequencies. The input can contain richer objects than the keys being counted.
A simple example
countBy
- Start with A, B, A
- Do this Count each key
- Result A has 2, B has 1
Syntax
orders.countBy { it.status }
Run this example in Groovy
Save the program as Lesson.groovy. Use Groovy 4 on the JVM.
groovy Lesson.groovy
Count records by an extracted key
An operations report receives repeated statuses or events. Decide whether it needs totals, consecutive runs or a snapshot before grouping so the summary preserves the distinctions the operator needs.
def orders = [[status: 'new'], [status: 'sent'], [status: 'new']]
def counts = orders.countBy { it.status }
['new', 'sent', 'held'].each { key ->
println key + '=' + counts.getOrDefault(key, 0)
}
new=2 sent=1 held=0
Use an explicit list of requested categories when a report must include zero-count rows. The map has an entry only for a status actually encountered.
Groovy documentation for countBy
Count north-door returns
A gallery receives entrance codes from four ticket desks. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?
Count ready print jobs
A print desk groups the current jobs by status. Count how often the specified code occurs when grouping the records. Which count belongs on that code’s row?