1

I have an array of strings and I am trying to look for the string that matches a certain regex. As soon as it finds the first match, I would like to break/exit out of the each loop. My code is

imagePathPrefix = "aab"
destinations.each{
  if(it.startsWith(imagePathPrefix)){
  // As soon as the first match is found, do something and then exit out of each !
}

destination looks like

[aabb, aabbbbb, abbbb, aaaaaabb, abababa]

As soon as it matches with aabb, I would like to exit/break out of the each loop.

EDIT:

Ive added return true but it does not work

destinations = ['aabb', 'abbbb', 'aaaaaabb', 'abababa']

println destinations

println destinations.getClass()

destinations.each{
    if(it.startsWith('aab')){
        println "a found"
        return true
    } else {
        println "a not found"
    }
}​

Result:

[aabb, abbbb, aaaaaabb, abababa]
class java.util.ArrayList
a found
a not found
a not found
a not found
Jason Stanley
  • 386
  • 1
  • 3
  • 20
  • Does this answer your question? [is it possible to break out of closure in groovy](https://stackoverflow.com/questions/1336704/is-it-possible-to-break-out-of-closure-in-groovy) – cfrick Sep 16 '20 at 16:28
  • Rule of thumb: `each` is for sideeffects only – cfrick Sep 16 '20 at 16:29

1 Answers1

4

The groovy way to find the first element of a collection that meet some condition is to use find

println destinations.find {it.startsWith(imagePathPrefix)}

returns for your data

aabb   
Marmite Bomber
  • 19,886
  • 4
  • 26
  • 53