Ryan
Ryan

Reputation: 1360

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.

Upvotes: 12

Views: 9280

Answers (4)

Nathan Hughes
Nathan Hughes

Reputation: 96385

You could use grep:

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

Upvotes: 1

ataylor
ataylor

Reputation: 66059

Alternatively, you can do this as a fold operation with inject:

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

This iterates the whole list and concatenates each successive element to a result, with logic to use the empty string for null elements.

Upvotes: 2

epidemian
epidemian

Reputation: 19219

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

Upvotes: 10

cdeszaq
cdeszaq

Reputation: 31280

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.

Upvotes: 13

Related Questions