Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get next iterator value in Groovy

Tags:

loops

groovy

How can I get the next value of iterator while looping through a collection with Groovy 1.7.4

values.each {it ->
    println(it)
    println(it.next()) //wrong
}
like image 294
Jacob Avatar asked Dec 01 '22 20:12

Jacob


1 Answers

Another way to get access to the previous element is with List.collate. By setting the step parameter to 1, you can get a "sliding window" view of your collection:

def windowSize = 2
def values = [ 1, 2, 3, 4 ]
[null, *values].collate(windowSize, 1, false).each { prev, curr ->
    println "$prev, $curr"
}

The list has to be padded with null at the beginning to provide the first element's prev.

like image 104
ataylor Avatar answered Dec 04 '22 12:12

ataylor