如何检查列表是否包含子列表 [英] how to check if a list contains a 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)
printlnfound $ {it}
}
}
我想检查大列表( list
)是否包含子列表的所有元素( l
)
Groovy是否有内置的方法来检查这个或者我在上面的代码中会做些什么?
您可以使用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)
这篇关于如何检查列表是否包含子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!