我是groovy的新手所以我有一个问题,我有两个列表,我想知道第一个列表中存在的值是否也存在于第二个列表中,并且它必须返回true或false。
我试着做一个简短的测试,但它不起作用......这是我试过的:
// List 1
def modes = ["custom","not_specified","me2"]
// List 2
def modesConf = ["me1", "me2"]
// Bool
def test = false
test = modesConf.any { it =~ modes }
print test
但如果我将第一个数组中“me2”的值更改为“mex2”,则必须返回false时返回true
有什么想法吗?
答案 0 :(得分:7)
我相信你想要:
// List 1
def modes = ["custom","not_specified","me2"]
// List 2
def modesConf = ["me1", "me2"]
def test = modesConf.any { modes.contains( it ) }
print test
答案 1 :(得分:7)
最简单的我可以想到使用intersect
并让Groovy真相开始。
def modes = ["custom","not_specified","me2"]
def modesConf = ["me1", "me2"]
def otherList = ["mex1"]
assert modesConf.intersect(modes) //["me2"]
assert !otherList.intersect(modes) //[]
assert modesConf.intersect(modes) == ["me2"]
如果断言通过,您可以在不进行第二次操作的情况下从交叉点中获取公共元素。 :)
答案 2 :(得分:4)
如果没有两个列表共有的项目,则此disjoint()
方法返回true
。听起来你想要否定这一点:
def modes = ["custom","not_specified","me2"]
def modesConf = ["me1", "me2"]
assert modes.disjoint(modesConf) == false
modesConf = ["me1", "mex2"]
assert modes.disjoint(modesConf) == true
答案 3 :(得分:0)
您可以使用任何将返回true / false的disjoint()/ intersect()/ any({})。下面是给出的例子:
def list1=[1,2,3]
def list2=[3,4,5]
list1.disjoint(list2) // true means there is no common elements false means there is/are
list1.any{list2.contains(it)} //true means there are common elements
list1.intersect(list2) //[] empty list means there is no common element.
答案 4 :(得分:0)
def missingItem = modesConf.find { !modes.contains(it) }
assert missingFile == "me1"
在这种情况下,missingItem将包含一个丢失的元素,该元素存在于modesConf中,但不存在于modes中。如果一切正常,则为null。