Search

Dark theme | Light theme

April 29, 2010

Groovy Goodness: Using the Subscript Operator on Iterators

Since Groovy 1.7.2 we can use the subscript operator for the Iterator class through the getAt() method. But we have to keep in mind the index value we use depends on a previous invocation of the subscript operator. Let's see this with an example:

def list = ['Groovy', 'Grails', 'Griffon', 'Gradle']
def iterator = list.iterator()

assert 'Groovy' == iterator[0]
assert 'Gradle' == iterator[-1]
assert !iterator[1]  // Iterator is exhausted.

iterator = list.iterator()  // Get new iterator.
def newList = []
(0..<list.size()).each {
 newList << iterator[0]  // Index 0 is next element.
}
assert 'Groovy,Grails,Griffon,Gradle' == newList.join(',')