如何使用"继续"在groovy的每个循环中

时间:2017-01-04 14:02:46

标签: for-loop groovy each spock continue

我是groovy的新手(曾在java上工作),尝试使用Spock框架编写一些测试用例。 我需要将以下Java代码段转换为groovy代码段,使用"每个循环"

Java代码段:

List<String> myList = Arrays.asList("Hello", "World!", "How", "Are", "You");
for( String myObj : myList){
    if(myObj==null) {
        continue;   // need to convert this part in groovy using each loop
    }
    System.out.println("My Object is "+ myObj);
}

Groovy Snippet:

def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ myObj->
    if(myObj==null){
        //here I need to continue
    }
    println("My Object is " + myObj)
}

3 个答案:

答案 0 :(得分:36)

使用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)
}

答案 1 :(得分:14)

您可以使用标准continue循环for( String myObj in myList ){ if( something ) continue doTheRest() }

return

或在each关闭时使用myList.each{ myObj-> if( something ) return doTheRest() }

for (username in users) { ..

答案 2 :(得分:1)

如果对象不是if,您也只能输入null语句。

def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ 
    myObj->
    if(myObj!=null){
        println("My Object is " + myObj)
    }
}