1

该列表可以为空。我想要做 :

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"
4

2 回答 2

0

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

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

可以写:

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

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

于 2013-03-09T07:48:12.183 回答
0

如果List只是尝试

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

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

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

Java:从集合中获取第一个项目

于 2013-03-08T15:45:56.427 回答