How to use “continue” in groovy’s each loop

Either use return, as the closure basically is a method that is called with each element as parameter like

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

Or switch your pattern to

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

Or use a findAll before to filter out null objects

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

Or 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

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

Leave a Comment

tech