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?
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.
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.
You can use the built-in len() function to find how many items a nested sublist has.
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)
The easiest method is just to call:
list.containsAll(l)
You can find more information about it here: Groovy Collections
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With