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():

l=[1,2,33]
println l.size() // yields 3

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:

l=[1,2,33]
println l.count { it>3 } // yields 1

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

class obj {
    def i
    def j
    
    def obj(in_i, in_j) {
        i=in_i
        j=in_j
    }
    
    String toString() {
        return "obj($i, $j)"
    }
}

def a=new obj(1,1)
def b=new obj(1,2)
def c=new obj(1,3)
def list=[a, b, c]

println list.count { it.j>1 } // yields 2, i.e. counts b and c

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:

class obj {
    def i
    def j
    
    def obj(in_i, in_j) {
        i=in_i
        j=in_j
    }
    
    String toString() {
        return "obj($i, $j)"
    }
}

def a=new obj(1,1)
def b=new obj(1,2)
def c=new obj(1,3)
def list=[eins: a, zwei: b, drei: c]

println list.count { it.value.j>1 } // again yields 2

Hope that helps.  See you next time!