2013-08-30 128 views
3

即時通訊中的新手所以我有一個問題,我有兩個列表,並且我想知道第一個列表中是否存在第二個列表中存在的值,它必須返回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

任何想法?

回答

5

我相信你想:

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

def test = modesConf.any { modes.contains(it) } 
print test 
3

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 
6

最簡單的我能想到的是使用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"] 

如果斷言過去了,你可以得到普遍。沒有進行第二次操作就從交叉點出來的元素。 :)

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. 
相關問題