Remove null from list

Often times you want to iterate over a list that gets populate from database or data service that contains null elements. This example will show how to remove null elements from an arraylist in groovy. In the first snippet we will use the groovy subtraction operator and in the second we will call the minus method which is equivalent method name for -. A comparable example demonstrates how to remove null from a list in java using java 8, guava and apache commons.

Subtraction operator

@Test
void remove_null_from_collection() {

    def collection = [
            89,
            32,
            null,
            55
    ] - null

    assert [89, 32, 55], list

}

Minus method name

@Test
void remove_null_with_minus_from_collection() {

    def collection = [
            89,
            32,
            null,
            55
    ].minus(null)

    assert [89, 32, 55], collection
}