69

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

ex: [null, 30, null]

want to return: [30]

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
RyanLynch
  • 2,987
  • 3
  • 35
  • 48
  • 2
    Funny that nobody asked how the nulls ended up in the list in the first place. Seems like you might be addressing the symptom rather than the problem. – Snekse Jan 28 '15 at 23:13

8 Answers8

148

Just use minus:

[null, 30, null] - null
Sergei
  • 1,481
  • 2
  • 9
  • 2
  • 12
    One can also use [null, 30, null].minus(null).That seems more readable to me. Version with '-' reminds about SBT operator abuse. – Mikhail Boyarsky Dec 08 '15 at 19:50
87

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

tim_yates
  • 167,322
  • 27
  • 342
  • 338
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
54

The findAll method should do what you need.

​[null, 30, null]​.findAll {it != null}​
Chris Dail
  • 25,715
  • 9
  • 65
  • 74
18

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]]
Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29
Dino Fancellu
  • 1,974
  • 24
  • 33
12

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]​
MKB
  • 7,587
  • 9
  • 45
  • 71
  • New location for docs: [grep](https://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Collection.html#grep(java.lang.Object)) – RomanMitasov May 19 '22 at 09:24
2

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

Alexander Suraphel
  • 10,103
  • 10
  • 55
  • 90
Kasper Ziemianek
  • 1,329
  • 8
  • 15
2

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

Anonymous1
  • 3,877
  • 3
  • 28
  • 42
2

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 }
B. Anderson
  • 3,079
  • 25
  • 33