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

时间:2011-01-29 22:22:31

标签: list groovy idiomatic

让代码先发言

def bars = foo.listBars()
def firstBar = bars ? bars.first() : null
def firstBarBetter = foo.listBars()?.getAt(0)

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

3 个答案:

答案 0 :(得分:55)

不确定使用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 }

答案 1 :(得分:15)

您也可以

foo[0]

当foo为null时,这将抛出NullPointerException,但它会在空列表上返回一个空值,这与foo.first()不同,后者会在空的情况下抛出异常。

答案 2 :(得分:2)

从Groovy 1.8.1开始,我们可以使用方法 take()和drop()。使用 take()方法,我们从List 的开头获取项目。我们将我们想要的项目数作为参数传递给方法。

要从List的开头删除项目,我们可以使用drop()方法。传递要删除的项目数作为方法的参数。

请注意原始列表未更改,take()/ drop()方法的结果是新列表。

def a = [1,2,3,4]

println(a.drop(2))
println(a.take(2))
println(a.take(0))
println(a)

*******************
Output:
[3, 4]
[1, 2]
[]
[1, 2, 3, 4]