Remove null items from a list in Groovy

Groovy

Groovy Problem Overview


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

ex: [null, 30, null]

want to return: [30]

Groovy Solutions


Solution 1 - Groovy

Just use minus:

[null, 30, null] - null

Solution 2 - Groovy

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

Solution 3 - Groovy

The findAll method should do what you need.

​[null, 30, null]​.findAll {it != null}​

Solution 4 - Groovy

I think you'll find that this is the shortest, assuming that you don't mind other "false" values also dissappearing:

println([null, 30, null].findAll())

> public Collection findAll() finds the items matching the IDENTITY > Closure (i.e. matching Groovy truth). > > Example: > > def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] > assert items.findAll() == [1, 2, true, 'foo', [4, 5]]

Solution 5 - Groovy

This can also be achieved by grep:

assert [null, 30, null].grep()​ == [30]​

or

assert [null, 30, null].grep {it}​ == [30]​

or

assert [null, 30, null].grep { it != null } == [30]​

Solution 6 - Groovy

Simply [null].findAll{null != it} if it is null then it return false so it will not exist in new collection.

Solution 7 - Groovy

Another way to do it is [null, 20, null].findResults{it}.

Solution 8 - Groovy

This does an in place removal of all null items.

myList.removeAll { !it }

If the number 0 is in your domain you can check against null

myList.removeAll { it == null }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyanLynchView Question on Stackoverflow
Solution 1 - GroovySergeiView Answer on Stackoverflow
Solution 2 - GroovyhvgotcodesView Answer on Stackoverflow
Solution 3 - GroovyChris DailView Answer on Stackoverflow
Solution 4 - GroovyDino FancelluView Answer on Stackoverflow
Solution 5 - GroovyMKBView Answer on Stackoverflow
Solution 6 - GroovyKasper ZiemianekView Answer on Stackoverflow
Solution 7 - GroovyAnonymous1View Answer on Stackoverflow
Solution 8 - GroovyB. AndersonView Answer on Stackoverflow