list 如何检查groovy数组/哈希/集合/列表中的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:17:13  来源:igfitidea点击:

How to check if element in groovy array/hash/collection/list?

arrayslistgroovy

提问by banderson623

How do I figure out if an array contains an element? I thought there might be something like [1, 2, 3].includes(1)which would evaluate as true.

如何判断数组是否包含元素?我认为可能有类似的东西[1, 2, 3].includes(1)会评估为true.

回答by dahernan

Some syntax sugar

一些语法糖

1 in [1,2,3]

回答by shemnon

.contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()

.contains() 是列表的最佳方法,但对于地图,您需要使用 .containsKey() 或 .containsValue()

[a:1,b:2,c:3].containsValue(3)
[a:1,b:2,c:3].containsKey('a')

回答by banderson623

For lists, use contains:

对于列表,请使用contains

[1,2,3].contains(1) == true

回答by John Flinchbaugh

If you really want your includes method on an ArrayList, just add it:

如果您真的希望在 ArrayList 上使用包含方法,只需添加它:

ArrayList.metaClass.includes = { i -> i in delegate }

回答by Twelve24

IMPORTANT Gotcha for using .contains() on a Collection of Objects, such as Domains. If the Domain declaration contains a EqualsAndHashCode, or some other equals() implementation to determine if those Ojbects are equal, and you've set it like this...

在对象集合(例如域)上使用 .contains() 的重要问题。如果域声明包含 EqualsAndHashCode 或其他一些 equals() 实现来确定这些 Ojbects 是否相等,并且您已将其设置为这样...

import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode(includes = "settingNameId, value")

then the .contains(myObjectToCompareTo) will evaluate the data in myObjectToCompareTo with the data for each Object instance in the Collection. So, if your equals method isn't up to snuff, as mine was not, you might see unexpected results.

然后 .contains(myObjectToCompareTo) 将使用集合中每个对象实例的数据评估 myObjectToCompareTo 中的数据。所以,如果你的 equals 方法不符合标准,就像我的一样,你可能会看到意想不到的结果。

回答by HinataXV

def fruitBag = ["orange","banana","coconut"]
def fruit = fruitBag.collect{item -> item.contains('n')}

I did it like this so it works if someone is looking for it.

我是这样做的,所以如果有人正在寻找它,它就可以工作。

回答by MagGGG

You can use Membership operator:

您可以使用 Membership 运算符:

def list = ['Grace','Rob','Emmy']
assert ('Emmy' in list)  

Membership operator Groovy

会员运营商 Groovy