[英]Get the first element of a list idiomatically in Groovy
讓代碼先說話
def bars = foo.listBars()
def firstBar = bars ? bars.first() : null
def firstBarBetter = foo.listBars()?.getAt(0)
是否有更優雅或慣用的方法來獲取列表的第一個元素,或者如果不可能,則為 null? (我不會在這里考慮優雅的 try-catch 塊。)
不確定使用 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 }
--更新 Groovy 1.8.1
你可以簡單地使用 foo?.find() 而不使用閉包。 它將返回列表中的第一個 Groovy Truth 元素,如果 foo 為 null 或列表為空,則返回 null。
你也可以這樣做
foo[0]
當 foo 為 null 時,這將拋出 NullPointerException,但它將在空列表上返回一個 null 值,不像foo.first()
會在空時拋出異常。
從 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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.