Search code examples
loopsgroovy

Get next iterator value in 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
}

Solution

  • So if you want to check the next item in the list (assuming it's a list), you can do:

    // 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" )
    }
    

    Or, you can use inject to store the previous value, and get:

    values[ 1..-1 ].inject( values[ 0 ] ) { prev, curr ->
        println "$prev $curr"
        curr
    }
    

    Or, you can just keep track of the previous element yourself with an each:

    def prev = null
    values.each { curr ->
      if( prev != null ) println "$prev $curr"
      prev = curr
    }