Count non empty strings in arraylist

In this example we will demonstrate how to count strings in a collection using groovy. We pass a closure to the count method where we will check if the string is not null and the length is greater than 0. In a comparable example we demonstrate how to count empty elements in java 8 and guava.

Count non null strings in collection

@Test
void count_non_empty_strings_in_arraylist() {

    def occurrences = [
        "packers",
        null,
        "",
        "fans",
        null,
        "Go pack Go!"
    ].count ({ it -> it != null && it.length() > 0 })

    assert 3, occurrences
}

Objects utility method was introduced in java 7 while the nonNull was added in java 8. This example will use the variation to check if the string is null.

@Test
void count_non_empty_strings_in_arraylist() {

    def occurrences = [
        "packers",
        null,
        "",
        "fans",
        null,
        "Go pack Go!"
    ].count ({ it -> Objects.nonNull(it) && it.length() > 0 })

    assert 3, occurrences
}