如何检查列表是否包含子列表 [英] how to check if a list contains a sublist

查看:130
本文介绍了如何检查列表是否包含子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆