Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a list contains a sublist

Tags:

groovy

def l = ["My", "Homer"]
String s = "Hi My Name is Homer"

def list = s.split(" ")
println list

list.each{it ->
    l.each{it1 ->
        if (it == it1)
            println "found ${it}"
    }
}

I want to check whether big list (list) contains all elements of sublist (l) Does groovy have any built in methods to check this or what I have in the above code will do?

like image 293
Omnipresent Avatar asked Dec 09 '09 03:12

Omnipresent


People also ask

How do you check whether a list contains a sublist?

issubset() function. The most used and recommended method to check for a sublist. This function is tailor made to perform the particular task of checking if one list is a subset of another.

How do you check if a list contains a sublist in Java?

You can use method Collections. indexOfSubList . Returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence. More formally, returns the lowest index i such that source.

How do you check the elements of a sublist in Python?

You can use the built-in len() function to find how many items a nested sublist has.


2 Answers

You could use Groovy's Collection.intersect(Collection right) method and check whether the returned Collection is as big as the one that's passed as argument.

You have to use the String.tokenize() method before to generate a List from the String instead of String.split() which returns a String array:

def sublist = ["My", "Homer"]
def list = "Hi My Name is Homer".tokenize()

assert sublist.size() == list.intersect(sublist).size()

Alternatively, you could use Groovy's Object.every(Closure closure) method and check if each element of the sublist is contained in the list:

assert sublist.every { list.contains(it) }

However, the shortest way is using the standard Java Collection API:

assert list.containsAll(sublist)
like image 191
Christoph Metzendorf Avatar answered Nov 16 '22 11:11

Christoph Metzendorf


The easiest method is just to call:

list.containsAll(l)

You can find more information about it here: Groovy Collections

like image 32
Brandon Avatar answered Nov 16 '22 13:11

Brandon