Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy, how to iterate a list with an index

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 } 
like image 954
raffian Avatar asked Mar 01 '12 19:03

raffian


People also ask

How do you get the index of an element in a list in Groovy?

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.

How do I iterate over a list?

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().

How does for loop work in groovy?

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.

What is each in groovy?

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.


1 Answers

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 
like image 155
ataylor Avatar answered Sep 27 '22 20:09

ataylor