在 Groovy 中以惯用方式获取列表的第一个元素 [英] Get the first element of a list idiomatically in Groovy

查看:36
本文介绍了在 Groovy 中以惯用方式获取列表的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让代码先说话

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

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

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

推荐答案

不确定使用 find 是否最优雅或最惯用,但它简洁且不会抛出 IndexOutOfBoundsException.

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 }  

<小时>

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


--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 中以惯用方式获取列表的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆