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.
Let's say we want to concatenate the elements of a String array where any of the elements may be null. But, we may not want to display or append such “null” values to the output. We cannot avoid null elements from being concatenated while using the String.
Concatenating Data When There Are NULL Values To resolve the NULL values in string concatenation, we can use the ISNULL() function. In the below query, the ISNULL() function checks an individual column and if it is NULL, it replaces it with a space. We can verify the output of the data as shown below.
In Groovy, there is a subtle difference between a variable whose value is null and a variable whose value is the empty string. The value null represents the absence of any object, while the empty string is an object of type String with zero characters.
Groovy - isEmpty() Returns true if this List contains no elements.
The concatenation of strings can be done by the simple '+' operator. Parameters − The parameters will be 2 strings as the left and right operand for the + operator.
To concatenate null to a string, use the + operator. Let's say the following is our string. String str = "Demo Text"; We will now see how to effortlessly concatenate null to string.
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.
If you use findAll
with no parameters. It will return every "truthful" value, so this should work:
def ans = [part1, part2, part3].findAll().join()
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 to join()
:)
If this is a simplified question and you want to keep empty string values, you can use findResults
{ it }
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With