带空检查的Groovy字符串连接 [英] Groovy String concatenation with null checks

查看:156
本文介绍了带空检查的Groovy字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方法来做到这一点?注意: part1 part2 part3 是定义的字符串变量其他地方(它们可以为null)。

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

所需的结果是一个空字符串连接的字符串。

解决方案

您可以这样做:

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

您可能能够将关闭缩小到 {it} ,具体取决于您的列表项目将如何评估 Groovy Truth ,但这会让它变得更紧张。



注意: GDK javadoc 是一个很好的资源。 p>

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.

解决方案

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.

这篇关于带空检查的Groovy字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆