【问题标题】:Is there a functional programming way to retrieve the first element of a collection?有没有一种函数式编程方法来检索集合的第一个元素?
【发布时间】:2013-02-24 04:55:24
【问题描述】:

列表可以为空。我想做:

def value = "";
def list = getList()
if (!list.isEmpty()){
   value = list.first().foo 
}

例如我发现了这种方式:

assert ( [].find()?.foo?:"empty" ) == "empty"
assert ([[foo:"notEmpty1"], [foo:"notEmpty2"]].find()?.foo?:"empty") == "notEmpty1"

有没有更好的方法?

谢谢! :)

编辑:

我使用[0]得到了很好的答案

assert ( [][0]?.foo?:"empty" ) == "empty"
assert ([[foo:"notEmpty1"], [foo:"notEmpty2"]][0]?.foo?:"empty") == "notEmpty1"

【问题讨论】:

  • 为什么不list?.get(0)
  • 列表不为空,但可以为空。所以list?.get(0) 会抛出一个 IndexOutOfBoundsException
  • 如果不是List,而是Collection,请阅读这篇文章stackoverflow.com/questions/1671378/…
  • 我同意我可以使用像番石榴这样的外部库,但我正在寻找一个 100% 的常规解决方案。
  • 在同一篇文章中你有它。由于 groovy 可以使用 java 的库,因此 java 解决方案是一个 groovy 解决方案。 100%

标签: groovy


【解决方案1】:

我从推特上得到了答复。声明:

def value = "";
def list = getList()
if (!list.isEmpty()){
   value = list.first().foo 
}

可以写:

def value = list[0]?.foo?:""

如果列表可以包含空值,则可以使用find

【讨论】:

    【解决方案2】:

    如果是List 试试

    if (!list?.isEmpty()){
        list.get(0);
    }
    

    如果列表元素不能为空,则不需要?

    如果它是一个集合,则有多种形式可以检索它。看看这个帖子

    Java: Get first item from a collection

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      • 2015-08-04
      • 2014-11-18
      • 1970-01-01
      • 2021-07-19
      相关资源
      最近更新 更多