Find if any value in a list exists in another list
Solution 1
Simplest I can think of is using intersect
and let Groovy truth kick in.
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"]
In case the assertion passed, you can get the common elements out of the intersection without doing a second operation. :)
Solution 2
I believe you want:
// List 1
def modes = ["custom","not_specified","me2"]
// List 2
def modesConf = ["me1", "me2"]
def test = modesConf.any { modes.contains( it ) }
print test
Solution 3
This disjoint()
method returns true
if there's no item that is common to both lists. It sounds like you want the negation of that:
def modes = ["custom","not_specified","me2"]
def modesConf = ["me1", "me2"]
assert modes.disjoint(modesConf) == false
modesConf = ["me1", "mex2"]
assert modes.disjoint(modesConf) == true
Solution 4
You can use any of the disjoint()/intersect()/any({}) which will return true/false. Below given are the examples:
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.
Ramiro Nava Castro
Updated on July 03, 2022Comments
-
Ramiro Nava Castro almost 2 years
im a newbie in groovy so i have a question, i have two lists, and i want to know if a value that exists in the first list also exists in the second list, and it must return true or false.
I tried to make a short test but it doesn't works... here is what i tried:
// 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
but if i change the value of "me2" in the first array to "mex2" it returns true when it must return false
Any idea?
-
feedy over 2 yearsThis only returns the first element that is missing, not all. If anyone wants to find all elements that are different, replace
find
withfindAll