Groovy String concatenation with null checks

concatenationgroovynullstring

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.

Best Answer

You can do this:

def ans = [part1, part2, part3].findAll({it != null}).join()

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.