Search

Dark theme | Light theme

December 7, 2009

Groovy Goodness: Counting the Items in a List

In Groovy we can count how many thimes a specific object is in a list. We use the count() method on the list, iterator or array to achieve this. We must specify one parameter: the object we want to count. Groovy uses the compareTo or equals() method to check for equality.

def list = [0, 1, 2, 1, 1, 3, 2, 0, 1]

assert 9 == list.size()
assert 2 == list.count(0)
assert 4 == list.count(1)
assert 2 == list.count(2)
assert 1 == list.count(3)