For loop 如何使用;“继续”;在groovy中';每个循环都是什么
我是groovy新手(在java上工作),尝试使用Spock框架编写一些测试用例。 我需要使用“每个循环”将以下Java代码段转换为groovy代码段 Java代码段:For loop 如何使用;“继续”;在groovy中';每个循环都是什么,for-loop,groovy,each,spock,continue,For Loop,Groovy,Each,Spock,Continue,我是groovy新手(在java上工作),尝试使用Spock框架编写一些测试用例。 我需要使用“每个循环”将以下Java代码段转换为groovy代码段 Java代码段: 您可以使用标准的for循环和continue: for( String myObj in myList ){ if( something ) continue doTheRest() } 或者在每个的结束语中使用返回: myList.each{ myObj-> if( something ) return
您可以使用标准的
for
循环和continue
:
for( String myObj in myList ){
if( something ) continue
doTheRest()
}
或者在每个的结束语中使用返回
:
myList.each{ myObj->
if( something ) return
doTheRest()
}
如果对象不是
null
,也只能输入if
语句
def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{
myObj->
if(myObj!=null){
println("My Object is " + myObj)
}
}
或者使用
return
,因为闭包基本上是一个方法,每个元素作为参数调用,如
def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ myObj->
if(myObj==null){
return
}
println("My Object is " + myObj)
}
或者将您的模式切换到
def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ myObj->
if(myObj!=null){
println("My Object is " + myObj)
}
}
或者在前面使用findAll
来过滤null
对象
def myList = ["Hello", "World!", "How", "Are", null, "You"]
myList.findAll { it != null }.each{ myObj->
println("My Object is " + myObj)
}
如果在条件不满足的情况下有大量代码要执行,那么使用“继续”方法可能会更干净地复制代码。OP希望筛选条目,因此,
findAll{…}
是这里的首要答案+1 findAll的上一个版本看起来最差。但这不是更费时吗?那你不是在整个集合上迭代了两次吗?
def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ myObj->
if(myObj!=null){
println("My Object is " + myObj)
}
}
def myList = ["Hello", "World!", "How", "Are", null, "You"]
myList.findAll { it != null }.each{ myObj->
println("My Object is " + myObj)
}