Get the first element of a list idiomatically in Groovy

人走茶凉 提交于 2019-11-30 07:56:10

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 }

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.

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