10

我是 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

任何想法?

4

5 回答 5

13

我能想到的最简单的方法是使用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"]

如果断言通过,您可以将公共元素从交集中取出,而无需进行第二次操作。:)

于 2013-08-30T14:02:43.573 回答
9

我相信你想要:

// List 1
def modes = ["custom","not_specified","me2"]
// List 2
def modesConf = ["me1", "me2"]

def test = modesConf.any { modes.contains( it ) }
print test
于 2013-08-30T13:51:13.297 回答
8

如果两个列表都没有共同的项目,则此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
于 2013-08-30T13:51:40.297 回答
1

您可以使用任何将返回 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.
于 2013-08-30T17:11:18.743 回答
0
def missingItem = modesConf.find { !modes.contains(it) }

assert missingFile == "me1"

在这种情况下,missingItem 将包含一个缺失元素,该元素存在于模式配置中但不存在于模式中。如果一切正常,则为 null。

于 2019-01-23T21:38:56.377 回答