Computing the Count of Items in a Collection

To determine the number of items in a collection call its size() function. However, if you need to count a subset of items in a collection based on a particular condition, then use count().

If you provide a single value, it returns a count of occurrences of that value in the collection. For example, the following use of count('bbb') returns the number 2.

def list = ['aa','bbb','cccc','defgh','bbb','aa','defgh','defgh']
// If there are two or more 'bbb' then do something...
if (list.count('bbb') >= 2){ /* etc. */ }
The count() function also accepts a boolean closure identifying which items to count. For example, to count the strings in a list whose lengths are an even number of characters, use code like the following. The count reflects the items for which the closure evaluates to true.
def list = ['aa','bbb','cccc','defgh','bbb','aa','defgh','defgh']
def numEvenLengths = list.count{ it.length() % 2 == 0 }
To partition the collection into distinct groups by a grouping expression and then count the number of items in each group, use the countBy() function. It takes a closure that identifes the grouping key before computing the count of the items in each group. For example, to count the number of occurrences of items in the list above, use:
def entriesAndCounts = list.countBy{ it }
This will produce a resulting map like this:
[aa:2, bbb:2, cccc:1, defgh:3]
If you want to sort the result descending by the number of occurrences of the strings in the list, use:
def entriesAndCounts = list.countBy{ it }
                           .sort{ a, b -> b.value <=> a.value }
Which produces the map:
[defgh:3, aa:2, bbb:2, cccc:1]
If you only care about the map entry containing the word that occurred the most frequently and its count of occurrences, then you can further chain the unqualified find() function that returns the first element.
def topWord = list.countBy{ it }
                  .sort{ a, b -> b.value <=> a.value }
                  .find()
println "Top word '${topWord.key}' appeared ${topWord.value} times"