在Groovy中以惯用方式获取列表的第一个元素

Ada*_*deg 30 groovy list idiomatic

让代码先发言

def bars = foo.listBars()
def firstBar = bars ? bars.first() : null
def firstBarBetter = foo.listBars()?.getAt(0)
Run Code Online (Sandbox Code Playgroud)

是否有更优雅或惯用的方式来获取列表的第一个元素,如果不可能则为null?(我不会在这里考虑优雅的试试块.)

Joh*_*ner 58

不确定使用find是最优雅还是惯用,但它简洁并且不会抛出IndexOutOfBoundsException.

def foo 

foo = ['bar', 'baz']
assert "bar" == foo?.find { true }

foo = []
assert null == foo?.find { true }

foo = null
assert null == foo?.find { true }
Run Code Online (Sandbox Code Playgroud)

  • +1这个技巧.我可以使它更简洁:`foo?.find {it}` (8认同)
  • 从Groovy 1.8.1开始,你可以简单地使用`foo?.find()`而不用闭包.它将返回列表中的第一个Groovy Truth元素,如果foo为null或列表为空,则返回null.[源(http://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Collection.html#find()) (4认同)
  • Adam,[0] .find {it}返回null (3认同)
  • 这将为Groovy地图添加一个非常方便的方法作为"first()" (2认同)

Jam*_*hon 17

你也可以这样做

foo[0]
Run Code Online (Sandbox Code Playgroud)

这将抛出一个NullPointerException当foo是空的,但它会空列表,不像返回空值foo.first(),这将扔在空异常.