【问题标题】:Get the first element of a list idiomatically in Groovy在 Groovy 中以惯用方式获取列表的第一个元素
【发布时间】:2011-06-17 21:52:41
【问题描述】:

让代码先说话

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

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

【问题讨论】:

  • #listBars 返回什么?如果您尝试从列表中获取不存在的元素,Groovy 不应该抛出异常。 final l = []assert l[0] == nullassert l.getAt(0) == nullassert l instanceof ArrayList

标签: list groovy idioms


【解决方案1】:

不确定使用 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。

【讨论】:

  • 这个技巧+1。我可以让它更简洁:foo?.find{ it }
  • 亚当,[0].find{it} 返回 null
  • 这将为 Groovy 映射添加一个非常方便的方法,如“first()”
  • 我知道这是一个较旧的线程,但我正在寻找类似的答案。起初我尝试了“foo?[0]”语法。我认为那会很酷,所以你也可以做 "foo?[1]", "foo?[2]",...。
  • 从 Groovy 1.8.1 开始,您可以简单地使用 foo?.find() 而无需关闭。它将返回列表中的第一个 Groovy Truth 元素,如果 foo 为 null 或列表为空,则返回 null。 source
【解决方案2】:

你也可以

foo[0]

这将在 foo 为 null 时抛出 NullPointerException,但它会在空列表上返回 null 值,不像 foo.first() 会在空时抛出异常。

【讨论】:

  • 感谢分享!我在 findAll 之后的第一个元素的惯用解决方案上陷入困境,该列表可能首先为空,或者在 findAll 之后,这给了我我需要的东西
【解决方案3】:

从 Groovy 1.8.1 开始,我们可以使用方法 take() 和 drop()。使用 take() 方法,我们从列表的开头获取项目。我们将我们想要的项目数作为参数传递给该方法。

要从列表的开头删除项目,我们可以使用 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]

【讨论】:

猜你喜欢
  • 2013-08-06
  • 2016-12-31
  • 2020-07-31
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-12
相关资源
最近更新 更多