RyanLynch
RyanLynch

Reputation: 3007

Remove null items from a list in Groovy

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

ex: [null, 30, null]

want to return: [30]

Upvotes: 71

Views: 60079

Answers (8)

Dino Fancellu
Dino Fancellu

Reputation: 2004

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]]

Upvotes: 21

B. Anderson
B. Anderson

Reputation: 3179

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 }

Upvotes: 2

Anonymous1
Anonymous1

Reputation: 3907

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

Upvotes: 2

MKB
MKB

Reputation: 7619

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]​

Upvotes: 12

Kasper Ziemianek
Kasper Ziemianek

Reputation: 1349

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

Upvotes: 2

Sergei
Sergei

Reputation: 1511

Just use minus:

[null, 30, null] - null

Upvotes: 151

hvgotcodes
hvgotcodes

Reputation: 120188

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

Upvotes: 89

Chris Dail
Chris Dail

Reputation: 26029

The findAll method should do what you need.

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

Upvotes: 54

Related Questions