如何在Groovy的each循环中使用“continue”

lc8prwob  于 2023-04-11  发布在  其他
关注(0)|答案(3)|浏览(476)

我是新的groovy(工作在java),试图写一些测试用例使用斯波克框架。我需要以下Java片段转换成groovy片段使用“每个循环”

Java Snippet:

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

qvk1mo1f1#

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

或者,如果您担心首先遍历整个集合以进行筛选,然后才从each开始,那么也可以利用Java流

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

8nuwlpux2#

你可以使用标准的for循环和continue

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

或者在each的闭包中使用return

myList.each{ myObj->
  if( something ) return
  doTheRest()
}
py49o6xq

py49o6xq3#

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

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

相关问题