Groovy Null Valid String Concatenation

Is there a better way to do this? Note: part1 , part2 and part3 are string variables defined elsewhere (they may be empty).

 def list = [part1, part2, part3] list.removeAll([null]) def ans = list.join() 

The desired result is a concatenated string with empty values.

+6
source share
4 answers

You can do it:

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

You may be able to shorten the closure to {it} depending on how your list items are ranked according to Groovy True , but that should make it a little denser.

Note. GDK javadocs is a great resource.

+9
source

If you use findAll without parameters. It will return every "true" value, so this should work:

 def ans = [part1, part2, part3].findAll().join() 

Note that findAll will filter out empty lines (because they are calculated as false in a boolean context), but in this case it does not matter, since empty lines do not add anything to join() :)

If this is a simplified question, and you want to keep empty string values, you can use findResults { it } .

+4
source

Alternatively, you can do this as an addition operation with inject :

 def ans = [part1, part2, part3].inject('') { result, element -> result + (element ?: '') } 

Iterates the entire list and combines each subsequent element with the result, with the logic for using an empty string for null elements.

+2
source

You can use grep :

 groovy:000> list = ['a', 'b', null, 'c'] ===> [a, b, null, c] groovy:000> list.grep {it != null}.join() ===> abc 
+1
source

Source: https://habr.com/ru/post/911134/


All Articles