Is there a better way to do this? Note: part1
, part2
and part3
are string variables defined elsewhere (they can be null).
def list = [part1, part2, part3]
list.removeAll([null])
def ans = list.join()
The desired result is a concatenated string with null values left out.
You can do this:
You might be able to shrink the closure down to just
{it}
depending on how your list items will evaluate according to Groovy Truth, but this should make it a bit tighter.Note: The GDK javadocs are a great resource.
You could use
grep
:Alternatively, you can do this as a fold operation with
inject
:This iterates the whole list and concatenates each successive element to a result, with logic to use the empty string for null elements.
If you use
findAll
with no parameters. It will return every "truthful" value, so this should work:Notice that
findAll
will filter out empty strings (because they are evaluated as false in a boolean context), but that doesn't matter in this case, as the empty strings don't add anything tojoin()
:)If this is a simplified question and you want to keep empty string values, you can use
findResults
{ it }
.