Get the first element of a list idiomatically in Groovy

青春壹個敷衍的年華 提交于 2019-11-29 10:44:26

问题


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.)


回答1:


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

def foo 

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

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

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



回答2:


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.




回答3:


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.

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.

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

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]


来源:https://stackoverflow.com/questions/4839834/get-the-first-element-of-a-list-idiomatically-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!