Groovy String concatenation with null checks

2019-06-17 08:32发布

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.

4条回答
▲ chillily
2楼-- · 2019-06-17 08:39

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.

查看更多
贪生不怕死
3楼-- · 2019-06-17 08:41

You could use grep:

groovy:000> list = ['a', 'b', null, 'c']
===> [a, b, null, c]
groovy:000> list.grep {it != null}.join()
===> abc
查看更多
欢心
4楼-- · 2019-06-17 08:51

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.

查看更多
霸刀☆藐视天下
5楼-- · 2019-06-17 09:03

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

查看更多
登录 后发表回答