Loading...

April 27, 2011

Groovy Goodness: Count Occurrences in a Collection or Map

We can count occurrences of elements in a collection that apply to a condition given by a closure. The closure contains the condition the elements we want to count must apply to. We can use the new count() method since Groovy 1.8 and it can be applied to collections, maps and arrays.

def list = ['Groovy', 'Grails', 'Java']
assert list.count { it.startsWith('G') } == 2

def numbers = [1,2,3,4] as Integer[]
assert numbers.count { it > 2 } == 2

def map = [user: 'mrhaki', city: 'Tilburg', age: 37]
assert map.count { key, value -> key.size() == 3 } == 1