gpt4 book ai didi

for-loop - 如何在groovy的each循环中使用 "continue"

转载 作者:行者123 更新时间:2023-12-02 18:39:20 67 4
gpt4 key购买 nike

我是 groovy 的新手(在 java 上工作),尝试使用 Spock 框架编写一些测试用例。我需要使用“each循环”将以下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);
}

精彩片段:

def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ myObj->
if(myObj==null){
//here I need to continue
}
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)
}

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

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

关于for-loop - 如何在groovy的each循环中使用 "continue",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41465691/

67 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com