tags:

views:

84

answers:

2

What is the best way to remove null items from a list in Groovy?

ex: [null, 30, null]

want to return: [30]

+6  A: 

The findAll method should do what you need.

​[null, 30, null]​.findAll {it != null}​
Chris Dail
+1 for a solution that does not change the original list
Pablo Fernandez
+3  A: 

here is an answer if you dont want to keep the original list

void testRemove() {
    def list = [null, 30, null]

    list.removeAll([null])

    assertEquals 1, list.size()
    assertEquals 30, list.get(0)
}

in a handy dandy unit test

hvgotcodes
+1 for the most readable solution (reads like: "remove all nulls")
Pablo Fernandez