0

How will I break the loop if a particular condition is satisfied?

My input file has around n number of lines. If the required information is got at some mth line I need to break the loop instead of reading the remaining lines.

new File("test.txt").readLines().reverseEach{line ->
   println line

   if(line.contains("Data"))
   break;
 }  
Kalaivani Ramesh
  • 11
  • 1
  • 1
  • 1

2 Answers2

3

You could use find to do this. Find ends the loop the first time the closure returns true and returns the last found element.

This

(1..20).find{
    println it
    it == 5
}

Would be the following in the groovy console.

1
2
3
4
5
Result: 5
hsan
  • 1,560
  • 1
  • 9
  • 12
  • Using 'find' like this assumes it's implemented as a single-threaded sequential algorithm in the version/implementation of Groovy you're using. – Vorg van Geir Feb 21 '13 at 10:08
  • @VorgvanGeir Ok, you have a point there. The groovy doc only states ["Finds the first item matching the IDENTITY Closure"](http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#find()). Just out of curiosity... are there any Groovy implementations that do this differently, e.g. multi-threaded or non-sequential? – hsan Feb 21 '13 at 10:38
0

You can't just break from closure. You can either throw an exception and exit from it, or do not use closures at all. Read all lines in array/list and iterate through it.

madhead
  • 31,729
  • 16
  • 153
  • 201