Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add only non-null item to a list in Groovy

Tags:

groovy

I want to add non null items to a List. So I do this:

List<Foo> foos = []
Foo foo = makeFoo()
if (foo)
    foos << foo

But is there a way to do it in a single operation (without using findAll after the creation of the list). Like:

foos.addNonNull(makeFoo())
like image 573
Thermech Avatar asked Nov 30 '22 21:11

Thermech


2 Answers

Another alternative is to use a short circuit expression:

foo && foos << foo

The foo variable must evaluate to true for the second part to be evaluated. This is a common practice in some other languages but I'd hesitate to use it widely in groovy due to readability issues and conventions.

like image 176
ataylor Avatar answered Dec 05 '22 00:12

ataylor


No, you'd need to use an if, or write your own addNonNull method (which just uses an if)

Also:

if( foo ) {

probably isn't enough, as this will skip empty strings, or 0 if it returns integers

You'd need

if( foo != null ) {
like image 36
tim_yates Avatar answered Dec 04 '22 22:12

tim_yates