在Groovy中获取下一个迭代器值

Jac*_*cob 4 groovy loops

在使用Groovy 1.7.4循环遍历集合时,如何获取迭代器的下一个值

values.each {it ->
    println(it)
    println(it.next()) //wrong
}
Run Code Online (Sandbox Code Playgroud)

ata*_*lor 9

另一种访问前一个元素的方法是使用List.collate.通过将step参数设置为1,您可以获得集合的"滑动窗口"视图:

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

列表必须在开头填充null以提供第一个元素prev.


tim*_*tes 8

因此,如果您想检查列表中的下一个项目(假设它是一个列表),您可以执行以下操作:

// Given a list:
def values = [ 1, 2, 3, 4 ]

// Iterate through it, printing out current and next value:
for( i = 0 ; i < values.size() ; i++ ) {
    def curr = values[ i ]
    def next = i < values.size() - 1 ? values[ i + 1 ] : null
    println( "$curr $next" )
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用inject存储以前的值,并获取:

values[ 1..-1 ].inject( values[ 0 ] ) { prev, curr ->
    println "$prev $curr"
    curr
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用每个元素自己跟踪前一个元素:

def prev = null
values.each { curr ->
  if( prev != null ) println "$prev $curr"
  prev = curr
}
Run Code Online (Sandbox Code Playgroud)