Groovy collections never fail to impress me. There are so many useful methods in Collections and count is one of them. Let’s take a look at 3 variants of this method

​def dataList = ['1','2','1','3','4','1','2','1','3','4']

count() method allows us to find out the number of occurrences of any data member in a collection

//Count occurrences of '1'
assert dataList.count('1') == 4

The second variant of count{} takes a closure input and below is one example of the same.

//Count all members not divisible by 2
assert dataList.count{it.toInteger()%2 == 1} == 6

countBy{} is very close variant of count. It sorts the collection in groups which are determined by closure. It also provides us the total number of elements in each group. The closure returns keys of the resulting Map and the frequency is stored as the value

//Count all members directly  divisible by 2  and not divisible by 2. Return the map with frequency
assert [1:6, 0:4] == dataList.countBy{it.toInteger() % 2}