Article
0 comment

Note to self: How to count things in Groovy collections

notetoselfThis time I would like to add a short note on how to find things in Groovy collections. Remember: collections is the general term for lists and maps, in other languages sometimes referred to as arrays or dictionaries.

Groovy has a standard method to count all elements of a collection. It is called size():

If you need to know the number of elements in a collection that fit a certain filter, it’s time to switch to count(). Count takes a closure and counts all elements, for which the closure yields true. This can bes as simple as counting all elements larger than 3:

Now what, if the elements of the list are  objects and I want to filter by a specific feature of the objects. No problem:

With maps it’s a bit more tricky. The it object inside the closure is of type LinkedHashMap$Entry, so we have to deal with its key and value attributes:

Hope that helps.  See you next time!

Leave a Reply

Required fields are marked *.