Library contents

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

  1. Start with A, B, A
  2. Do this Count each key
  3. Result A has 2, B has 1
The second A increases the existing A count from one to two.

Syntax

Groovy 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.

From the programprintln key + '=' + counts.getOrDefault(key, 0)
First output linenew=2
Lesson.groovy
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)
}
Output
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

Advertisements

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?

GivenN · S · N · N | count N
Worked result3

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?

Givenready · held · ready | count ready
Worked result2