是否有一种简单的语法或方便的方法(不用自己循环)来检查一个值是否存在于Map中( List中)?例如,我想做的是:
def myList = []
myList.push([first: "John", last: "Doe"])
println myList.contains(it -> it.first == "John")应该打印true,但语法不正确。基本上,我需要知道列表是否包含一个映射,在该映射中,“第一个”键的值是"John“。
发布于 2014-07-12 15:23:49
使用find可能是一个更好的解决方案:
def myList = []
myList.push([first: "John", last: "Doe"])
def exists = (myList.find{ it -> it.first == 'John'} ? true : false)
assert exists == true
exists = (myList.find{ it -> it.first == 'Jane'} ? true : false)
assert exists == false发布于 2014-07-12 18:34:06
另一个更简单的检查可能是使用spread操作符,如下所示
assert 'John' in myList*.first更新
如果列表大小较小,则对find和in之间的性能进行基准测试提供了倾向于使用in的结果。
Refer and run this GIST。结果可能会有所不同,但令人惊讶的是,当列表大小较小时,in相对于find消耗的CPU更少(如问题所示,请参阅第一个结果)。下面是在我编写此更新时记录的结果集。
user system cpu real
findTestWithSmallerListSize 571 0 571 598
inListTestWithSmallerListSize 411 0 411 411
findTestWithMatchPresentInEnd 2714872 43 2714915 2739768
inListTestWithMatchPresentInEnd 2266303 39 2266342 2431595
findTestWithMatchPresentInAverageCenter 2141836 39 2141875 2263714
inListTestWithMatchPresentInAverageCenter 2261387 37 2261424 2438485
findTestWithMatchPresentInFirst 1667364 27 1667391 1813254
inListTestWithMatchPresentInFirst 2288471 37 2288508 2425089基于上述结果,我同意,如果匹配出现在列表的开头或开始处(上面的第四个结果),那么find是完全有效的。
https://stackoverflow.com/questions/24714360
复制相似问题