Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if any value in a list exists in another list

Tags:

groovy

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?

like image 646
Ramiro Nava Castro Avatar asked Aug 30 '13 13:08

Ramiro Nava Castro


People also ask

How do you check if an element of a list is in another list Java?

contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

How do you check if a list is subset to another list in Python?

Using intersection The intersection function find the common elements between two sets. In this approach we convert the lists into sets and apply the intersection function. If the result of intersection is same as the sublist then we conclude the sublist is part of thelist.


2 Answers

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. :)

like image 150
dmahapatro Avatar answered Oct 02 '22 06:10

dmahapatro


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
like image 20
tim_yates Avatar answered Oct 02 '22 06:10

tim_yates