With all the shorthand ways of doing things in Groovy, there's got to be an easier way to iterate a list while having access to an iteration index.
for(i in 0 .. list.size()-1) { println list.get(i) }
Is there no implicit index in a basic for
loop?
for( item in list){ println item println index }
Groovy - indexOf() Returns the index within this String of the first occurrence of the specified substring. This method has 4 different variants. public int indexOf(int ch) − Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur.
Obtain an iterator to the start of the collection by calling the collection's iterator() method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true. Within the loop, obtain each element by calling next().
Groovy Programming Fundamentals for Java Developers S.No. The while statement is executed by first evaluating the condition expression (a Boolean value), and if the result is true, then the statements in the while loop are executed. The for statement is used to iterate through a set of values.
Introduction It is dynamically compiled to the Java Virtual Machine (JVM) bytecode, and inter-operates with other Java source codes and libraries. Groovy is written in Java and was first released in 2007. Groovy each and eachWithIndex methods are defined in Groovy Object, so we can use them for any object.
You can use eachWithIndex
:
list.eachWithIndex { item, index -> println item println index }
With Groovy 2.4 and newer, you can also use the indexed()
method. This can be handy to access the index with methods like collect
:
def result = list.indexed().collect { index, item -> "$index: $item" } println result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With