获取列表的第一个元素惯用Groovy中

问题描述:

让代码首先发言获取列表的第一个元素惯用Groovy中

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

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

+0

#listBars返回什么?如果您尝试获取列表中不存在的元素,Groovy不应该抛出。 `assert l.getAt(0)== null` `assert l instanceof ArrayList` – 2012-05-01 15:19:02

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

+1这个技巧。我可以使它更简洁:`foo?.find {it}` – 2011-02-09 11:50:26

+3

Adam,[0] .find {it}返回null – tixxit 2011-11-21 19:02:54

你也可以做

foo[0] 

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

由于Groovy 1.8.1我们可以使用方法take()和drop()。通过take()方法,我们从列表开始获得项目。我们将我们想要的项目的数量作为参数传递给方法。

要从列表开始处移除项目,我们可以使用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]