tags:

views:

161

answers:

3
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?

A: 

Your solution will work. Be sure to consider the Knuth–Morris–Pratt algorithm if you're dealing with large arrays of relatively few discrete values.

Matthew
He wasn't asking if his solution would work or not, he was asking if there were any built in functions that he could use to do this instead.
Gord
I am not aware of any.
Matthew
+3  A: 

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)
Christoph Metzendorf
A: 

The easiest method is just to call:

list.containsAll(l)

You can find more information about it here: Groovy Collections

Brandon