Remove null items from 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]

+42
groovy
Jul 19 '10 at 21:27
source share
8 answers

here is the answer if you do not 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 convenient dandy unit test

+56
Jul 19 '10 at 21:35
source share

Just use the minus:

 [null, 30, null] - null 
+97
Mar 11 2018-11-11T00:
source share

The findAll method should do what you need.

 ​[null, 30, null]​.findAll {it != null}​ 
+44
Jul 19 '10 at 21:29
source share

I think you will find that this is the shortest, assuming that you do not mind other β€œfalse” meanings that also disappear:

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

public Collection findAll () Searches for items matching an IDENTITY Closure (i.e., True Groovy). Example:

def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] assert items.findAll () == [1, 2, true, 'foo' , [4, 5]]

+9
Feb 02 '13 at 15:59
source share

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]​ 
+4
Jan 17 '15 at 9:27
source share

Just [null].findAll{null != it} , if it is null, then it returns false, so it will not exist in the new collection.

+2
Mar 19 '14 at 2:49
source share

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

0
Sep 27 '16 at 22:03
source share

This does the removal of all null elements.

 myList.removeAll { !it } 

If the number 0 is in your domain, you can check it for null

 myList.removeAll { it == null } 
0
Jun 13. '17 at 20:58
source share



All Articles