Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy - is there any implicit variable to get access to item index in "each" method

Tags:

groovy

Is there any way to remove variable "i" in the following example and still get access to index of item that being printed ?

def i = 0;
"one two three".split().each  {
    println ("item [ ${i++} ] = ${it}");
}

=============== EDIT ================

I found that one possible solution is to use "eachWithIndex" method:

"one two three".split().eachWithIndex  {it, i
    println ("item [ ${i} ] = ${it}");
}

Please do let me know if there are other solutions.

like image 834
mhshams Avatar asked Apr 30 '12 07:04

mhshams


People also ask

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

What does def mean in Groovy?

The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.

How do I print a value in Groovy script?

You can print the current value of a variable with the println function.


1 Answers

you can use eachWithIndex()

"one two three four".split().eachWithIndex() { entry, index ->
      println "${index} : ${entry}" }

this will result in

0 : one
1 : two
2 : three
3 : four
like image 74
murdochjohn Avatar answered Sep 23 '22 13:09

murdochjohn