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

How to use "continue" in groovy's each loop

我是 groovy 的新手(在 java 工作),尝试使用 Spock 框架编写一些测试用例。 我需要使用 "each loop"

将以下 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 片段:

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

您可以使用标准 for 循环 continue:

for( String myObj in myList ){
  if( something ) continue
  doTheRest()
}

或在each的闭包中使用return

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