查找列表中是否存在其他列表中的任何值

Ram*_*tro 6 groovy

我是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
Run Code Online (Sandbox Code Playgroud)

但是如果我将第一个数组中"me2"的值更改为"mex2",则它必须返回false时返回true

任何的想法?

dma*_*tro 9

我能想到的最简单的就是使用intersectGroovy真相.

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"]
Run Code Online (Sandbox Code Playgroud)

如果断言通过,您可以在不进行第二次操作的情况下从交叉点中获取公共元素.:)


tim*_*tes 8

我相信你想:

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

def test = modesConf.any { modes.contains( it ) }
print test
Run Code Online (Sandbox Code Playgroud)


bdk*_*her 7

如果没有两个列表共有的项目,则此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
Run Code Online (Sandbox Code Playgroud)