在Groovy中习惯性地获取列表的第一个元素 [英] Get the first element of a list idiomatically in Groovy

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

问题描述

让代码先说话

Let the code speak first

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

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