I am new to groovy (worked on java), trying to write some test cases using Spock framework. I need the following Java snippet converted into groovy snippet using "each loop"
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)
}
Either use
return
, as the closure basically is a method that is called with each element as parameter likeOr switch your pattern to
Or use a
findAll
before to filter outnull
objectsOr if you are concerned that you first iterate through the whole collection to filter and only then start with the
each
, you can also leverage Java streams