且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查列表是否包含子列表

更新时间:2022-10-15 10:23:55

您可以使用Groovy的 Collection.intersect(Collection right)方法,并检查返回的Collection是否与作为参数传递的Collection相同。

您必须先使用 String.tokenize()方法从String中生成List,而不是 String.split()它返回一个String数组:

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

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

另外,你可以使用Groovy的 Object.every(Closure closure )方法,并检查子列表的每个元素是否包含在列表中:

  assert子列表。每个{list.contains(it)} 

然而,最简单的方法是使用标准Java Collection API :

  assert list.containsAll(sublist)


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?

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)