How to check if a list contains sublists

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 if a large list ( list ) contains all the elements of the subscriptions ( l ) Are there any built-in methods for groovy for checking this or what I have in the above code?

+7
groovy
source share
3 answers

You can use the Groovy Collection.intersect(Collection right) method and check if the returned collection is as large as the argument passed as the argument.

You should use the String.tokenize() method earlier to generate a List from String instead of String.split() , which returns an array of String:

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

Alternatively, you can use the Groovy Object.every(Closure closure) method and check to see if each item has a sublist in the list:

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

However, the shortest way is to use the standard Java Collection API:

 assert list.containsAll(sublist) 
+18
source share

The easiest way is to simply call:

 list.containsAll(l) 

You can find more information about this here: Groovy Collections

+7
source share

Your solution will work. Be sure to consider the Knut-Morris-Pratt algorithm if you are dealing with large arrays of relatively few discrete values.

-2
source share

All Articles