Groovy String concatenation with null checks

独自空忆成欢 提交于 2019-12-23 08:38:07

问题


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.


回答1:


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.




回答2:


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




回答3:


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.




回答4:


You could use grep:

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


来源:https://stackoverflow.com/questions/9775951/groovy-string-concatenation-with-null-checks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!