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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4839834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:35:37  来源:igfitidea点击:

Get the first element of a list idiomatically in Groovy

listgroovyidiomatic

提问by Adam Schmideg

Let the code speak first

让代码先说话

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

Is there a more elegant or idiomatic way to get the first element of a list, or null if it's not possible? (I wouldn't consider a try-catch block elegant here.)

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

回答by John Wagenleitner

Not sure using find is most elegant or idiomatic, but it is concise and wont throw an IndexOutOfBoundsException.

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


--Update Groovy 1.8.1
you can simply use foo?.find() without the closure. It will return the first Groovy Truth element in the list or null if foo is null or the list is empty.

--更新 Groovy 1.8.1,
您可以简单地使用 foo?.find() 而不使用闭包。它将返回列表中的第一个 Groovy Truth 元素,如果 foo 为 null 或列表为空,则返回 null。

回答by James McMahon

You could also do

你也可以这样做

foo[0]

This will throw a NullPointerException when foo is null, but it will return a null value on an empty list, unlike foo.first()which will throw an exception on empty.

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

回答by Here_2_learn

Since Groovy 1.8.1 we can use the methods take() and drop(). With the take() method we get items from the beginning of the List. We pass the number of items we want as an argument to the method.

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

To remove items from the beginning of the List we can use the drop() method. Pass the number of items to drop as an argument to the method.

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

Note that the original list is not changed, the result of take()/drop() method is a new list.

注意原列表没有改变,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]