Count occurrences of element in list

In this example we will show how to count the number of times an element appears within a list. For seed data in the first snippet we used common gridiron football sport names and populated a list from 1 to 10 for the second. In both snippets we will use list.count passing a groovy closure with a clause. You can consider the count a short cut to filtering and finding the size of an arraylist. A comparable example demonstrates how to count the frequency of string or numbers in arraylist using java.

Count string starts with and contains

@Test
void count_elements_in_list () {

    def list = ["Six-man football", "Sprint", "Touch football"]

    def frequency = list.count { it.startsWith("S") && it.contains("football") }

    assert 1 == frequency
}

Count numbers greater than 7

@Test
void count_elements_gt_value() {

    def listOfNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    def rate = listOfNumbers.count { it > 7 }

    assert 3 == rate
}