Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy String concatenation with null checks

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.

like image 851
Ryan Avatar asked Mar 19 '12 18:03

Ryan


People also ask

Can we concatenate string with null?

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.

How do you concatenate null values?

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.

Can groovy string be null?

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.

How do you check if a string is empty in groovy?

Groovy - isEmpty() Returns true if this List contains no elements.

How do I concatenate strings in groovy?

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.

How do I append a null to a string?

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.


2 Answers

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.

like image 54
cdeszaq Avatar answered Sep 29 '22 14:09

cdeszaq


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 }.

like image 27
epidemian Avatar answered Sep 29 '22 12:09

epidemian