2

In groovy how to find the last iteration inside the closure.

def closure = { it->
   //here I need to print last line only
}

new File (file).eachLine{ closure(it)}

Need to find inside the closure iteration.

Update 1:

Instead of reading a file, In Common How can i find the last iteration inside the closure ?

def closure = { it->
   //Find last iteration here
}
Bhanuchander Udhayakumar
  • 1,581
  • 1
  • 12
  • 30

1 Answers1

3

I guess you need eachWithIndex:

def f = new File('TODO')
def lines = f.readLines().size()

def c = { l, i ->
    if(i == lines - 1) {
        println "last: $i $l"
    }
}

f.eachWithIndex(c)

Of course in case of big files you need to count lines efficiently.

Opal
  • 81,889
  • 28
  • 189
  • 210
  • Is there any simple way instead of this? – Bhanuchander Udhayakumar Oct 12 '17 at 11:05
  • 1
    @Bhanuchander_U what are you trying to achieve? – Opal Oct 12 '17 at 11:21
  • actually you did this with `f.readLines().size()`. but this file `readLine` which i put is for example. I want to check the final iteration inside the closure function only not from the source as you approach. – Bhanuchander Udhayakumar Oct 12 '17 at 11:27
  • 1
    @Bhanuchander_U, sorry I don't understand. If you want to check final iteration use for loop. It's not possible with `eachLine` closure. – Opal Oct 12 '17 at 11:34
  • Thanks for the response and suggestion bro. – Bhanuchander Udhayakumar Oct 12 '17 at 13:18
  • 1
    @Bhanuchander_U, if you find it useful, it is appreciated an up vote & consider accepting it as answered. If it does not answer your problem, question should clarify requested info by answerer instead of just thanks. You must understand that some one spent his precious time on your issue. – Rao Oct 12 '17 at 13:34