# Iterator Pattern

version 2.4.17

The Iterator Pattern allows sequential access to the elements of an aggregate object without exposing its underlying representation.

Groovy has the iterator pattern built right in to many of its closure operators, e.g. `each` and `eachWithIndex` as well as the `for .. in` loop.

For example:

    def printAll(container) {
        for (item in container) { println item }
    }

    def numbers = [ 1,2,3,4 ]
    def months = [ Mar:31, Apr:30, May:31 ]
    def colors = [ java.awt.Color.BLACK, java.awt.Color.WHITE ]
    printAll numbers
    printAll months
    printAll colors

Results in the output:

    1
    2
    3
    4
    May=31
    Mar=31
    Apr=30
    java.awt.Color[r=0,g=0,b=0]
    java.awt.Color[r=255,g=255,b=255]

Another example:

    colors.eachWithIndex { item, pos ->
        println "Position $pos contains '$item'"
    }

Results in:

    Position 0 contains 'java.awt.Color[r=0,g=0,b=0]'
    Position 1 contains 'java.awt.Color[r=255,g=255,b=255]'

The iterator pattern is also built in to other special operators such as the `eachByte`, `eachFile`, `eachDir`, `eachLine`, `eachObject`, `eachMatch` operators for working with streams, URLs, files, directories and regular expressions matches.