Iterator (Groovy JDK enhancements)

Package: java.util

## Interface Iterator

- - ### Methods Summary

    Methods
    Return type | Name and parameters
    --- | ---
    `boolean` | `any(Closure predicate)` Iterates over the contents of an iterator, and checks whether a predicate is valid for at least one element.
    `boolean` | `asBoolean()` Coerce an iterator instance to a boolean value.
    `Object` | `average()` Averages the items from an Iterator.
    `Object` | `average(Closure closure)` Averages the result of applying a closure to each item returned from an iterator.
    `BufferedIterator` | `buffered()` Returns a `BufferedIterator` that allows examining the next element without consuming it.
    `List` | `chop(int chopSizes)` Chops the iterator items into pieces, returning lists with sizes corresponding to the supplied chop sizes.
    `List` | `collect(Closure transform)` Iterates through this Iterator transforming each item into a new value using the `transform` closure, returning a list of transformed values.
    `Collection` | `collect(Collection collector, Closure transform)` Iterates through this Iterator transforming each item into a new value using the `transform` closure and adding it to the supplied `collector`.
    `Map` | `collectEntries()` A variant of collectEntries for Iterators using the identity closure as the transform.
    `Map` | `collectEntries(Closure transform)` A variant of collectEntries for Iterators.
    `Map` | `collectEntries(Map collector)` A variant of collectEntries for Iterators using the identity closure as the transform and a supplied map as the destination of transformed entries.
    `Map` | `collectEntries(Map collector, Closure transform)` A variant of collectEntries for Iterators using a supplied map as the destination of transformed entries.
    `List` | `collectMany(Closure projection)` Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.
    `Collection` | `collectMany(Collection collector, Closure projection)` Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.
    `Number` | `count(Closure closure)` Counts the number of occurrences which satisfy the given closure from the items within this Iterator.
    `Number` | `count(Object value)` Counts the number of occurrences of the given value from the items within this Iterator.
    `Map` | `countBy(Closure closure)` Sorts all iterator items into groups determined by the supplied mapping closure and counts the group size.
    `Iterator` | `drop(int num)` Drops the given number of elements from the head of this iterator if they are available.
    `Iterator` | `dropRight(int num)` Drops the given number of elements from the tail of this Iterator.
    `Iterator` | `dropWhile(Closure condition)` Creates an Iterator that returns a suffix of the elements from an original Iterator.
    `Iterator` | `each(Closure closure)` Iterates through an Iterator, passing each item to the given closure.
    `Iterator` | `eachWithIndex(Closure closure)` Iterates through an iterator type, passing each item and the item's index (a counter starting at zero) to the given closure.
    `boolean` | `every(Closure predicate)` Used to determine if the given predicate closure is valid (i.e. returns `true` for all items in this iterator).
    `int` | `findIndexOf(Closure condition)` Iterates over the elements of an Iterator and returns the index of the first item that satisfies the condition specified by the closure.
    `int` | `findIndexOf(int startIndex, Closure condition)` Iterates over the elements of an Iterator, starting from a specified startIndex, and returns the index of the first item that satisfies the condition specified by the closure.
    `List` | `findIndexValues(Closure condition)` Iterates over the elements of an Iterator and returns the index values of the items that match the condition specified in the closure.
    `List` | `findIndexValues(Number startIndex, Closure condition)` Iterates over the elements of an Iterator, starting from a specified startIndex, and returns the index values of the items that match the condition specified in the closure.
    `int` | `findLastIndexOf(Closure condition)` Iterates over the elements of an Iterator and returns the index of the last item that matches the condition specified in the closure.
    `int` | `findLastIndexOf(int startIndex, Closure condition)` Iterates over the elements of an Iterator, starting from a specified startIndex, and returns the index of the last item that matches the condition specified in the closure.
    `Object` | `findResult(Closure condition)` Iterates through the Iterator calling the given closure condition for each item but stopping once the first non-null result is found and returning that result.
    `Object` | `findResult(Object defaultResult, Closure condition)` Iterates through the Iterator calling the given closure condition for each item but stopping once the first non-null result is found and returning that result.
    `Collection` | `findResults(Closure filteringTransform)` Iterates through the Iterator transforming items using the supplied closure and collecting any non-null results.
    `Object` | `getAt(int idx)` Support the subscript operator for an Iterator.
    `Iterator` | `indexed()` Zips an iterator with indices in (index, value) order.
    `Iterator` | `indexed(int offset)` Zips an iterator with indices in (index, value) order.
    `Iterator` | `init()` Returns an Iterator containing all of the items from this iterator except the last one.
    `Object` | `inject(Object initialValue, Closure closure)` Iterates through the given Iterator, passing in the initial value to the closure along with the first item.
    `Iterator` | `iterator()` An identity function for iterators, supporting 'duck-typing' when trying to get an iterator for each object within a collection, some of which may already be iterators.
    `String` | `join(String separator)` Concatenates the `toString()` representation of each item from the iterator, with the given String as a separator between each item.
    `Object` | `max()` Adds max() method to Iterator objects.
    `Object` | `max(Closure closure)` Selects the maximum value found from the Iterator using the closure to determine the correct ordering.
    `Object` | `max(Comparator comparator)` Selects the maximum value found from the Iterator using the given comparator.
    `Object` | `min()` Adds min() method to Iterator objects.
    `Object` | `min(Closure closure)` Selects the minimum value found from the Iterator using the closure to determine the correct ordering.
    `Object` | `min(Comparator comparator)` Selects the minimum value found from the Iterator using the given comparator.
    `Iterator` | `reverse()` Reverses the iterator.
    `int` | `size()` Provide the standard Groovy `size()` method for `Iterator`.
    `Iterator` | `sort()` Sorts the given iterator items into a sorted iterator.
    `Iterator` | `sort(Closure closure)` Sorts the given iterator items into a sorted iterator using the Closure to determine the correct ordering.
    `Iterator` | `sort(Comparator comparator)` Sorts the given iterator items into a sorted iterator using the comparator.
    `Stream` | `stream()` Returns a sequential Stream with the specified element(s) as its source.
    `Object` | `sum()` Sums the items from an Iterator.
    `Object` | `sum(Closure closure)` Sums the result of applying a closure to each item returned from an iterator.
    `Object` | `sum(Object initialValue)` Sums the items from an Iterator, adding the result to some initial value.
    `Object` | `sum(Object initialValue, Closure closure)` Sums the result of applying a closure to each item of an Iterator to some initial value.
    `Iterator` | `tail()` Returns the original iterator after throwing away the first element.
    `Iterator` | `take(int num)` Returns an iterator of up to the first `num` elements from this iterator.
    `Iterator` | `takeWhile(Closure condition)` Returns the longest prefix of elements in this iterator where each element passed to the given condition closure evaluates to true.
    `List` | `toList()` Convert an iterator to a List.
    `Set` | `toSet()` Convert an iterator to a Set.
    `Iterator` | `toSorted()` Sorts the Iterator.
    `Iterator` | `toSorted(Closure closure)` Sorts the given iterator items into a sorted iterator using the Closure to determine the correct ordering.
    `Iterator` | `toSorted(Comparator comparator)` Sorts the given iterator items using the comparator.
    `Iterator` | `toUnique()` Returns an iterator equivalent to this iterator with all duplicated items removed by using the natural ordering of the items.
    `Iterator` | `toUnique(Closure condition)` Returns an iterator equivalent to this iterator but with all duplicated items removed where duplicate (equal) items are deduced by calling the supplied Closure condition.
    `Iterator` | `toUnique(Comparator comparator)` Returns an iterator equivalent to this iterator with all duplicated items removed by using the supplied comparator.
    `Iterator` | `unique()` Returns an iterator equivalent to this iterator with all duplicated items removed by using Groovy's default number-aware comparator.
    `Iterator` | `unique(Closure condition)` Returns an iterator equivalent to this iterator but with all duplicated items removed by using a Closure to determine duplicate (equal) items.
    `Iterator` | `unique(Comparator comparator)` Returns an iterator equivalent to this iterator with all duplicated items removed by using the supplied comparator.
    `Iterator` | `withIndex()` Zips an iterator with indices in (value, index) order.
    `Iterator` | `withIndex(int offset)` Zips an iterator with indices in (value, index) order.

- - ### Methods Detail

    - #### public boolean any(Closure predicate)

      Iterates over the contents of an iterator, and checks whether a predicate is valid for at least one element.

          assert [1, 2, 3].iterator().any { it == 2 }
          assert ![1, 2, 3].iterator().any { it > 3 }

      Parameters:
        `predicate` - the closure predicate used for matching
      Returns:
        true if any iteration for the object matches the closure predicate
      Since:
        1.0

    - #### public boolean asBoolean()

      Coerce an iterator instance to a boolean value. An iterator is coerced to false if there are no more elements to iterate over, and to true otherwise.

      Returns:
        the boolean value
      Since:
        1.7.0

    - #### public Object average()

      Averages the items from an Iterator. This is equivalent to invoking the "plus" method on all items in the array and then dividing by the total count using the "div" method for the resulting sum. The iterator will become exhausted of elements after determining the average value. While most frequently used with aggregates of numbers, `average` will work with any class supporting `plus` and `div`, e.g.:

          class Stars {
              int numStars = 0
              String toString() {
                  '*' * numStars
              }
              Stars plus(Stars other) {
                  new Stars(numStars: numStars + other.numStars)
              }
              Stars div(Number divisor) {
                  int newSize = numStars.intdiv(divisor)
                  new Stars(numStars: newSize)
              }
          }

          def stars = [new Stars(numStars: 1), new Stars(numStars: 3)]
          assert stars*.toString() == ['*', '***']
          assert stars.average().toString() == '**'

      Returns:
        The average of all of the items
      Since:
        3.0.0

    - #### public Object average(Closure closure)

      Averages the result of applying a closure to each item returned from an iterator. `iter.average(closure)` is equivalent to: `iter.collect(closure).average()`. The iterator will become exhausted of elements after determining the average value.

      Parameters:
        `closure` - a single parameter closure that returns a (typically) numeric value.
      Returns:
        The average of the values returned by applying the closure to each item from the Iterator.
      Since:
        3.0.0

    - #### public BufferedIterator buffered()

      Returns a `BufferedIterator` that allows examining the next element without consuming it.

          assert [1, 2, 3, 4].iterator().buffered().with { [head(), toList()] } == [1, [1, 2, 3, 4]]

      Returns:
        a BufferedIterator wrapping self
      Since:
        2.5.0

    - #### public List chop(int chopSizes)

      Chops the iterator items into pieces, returning lists with sizes corresponding to the supplied chop sizes. If the iterator is exhausted early, truncated (possibly empty) pieces are returned. Using a chop size of -1 will cause that piece to contain all remaining items from the iterator.

      Parameters:
        `chopSizes` - the sizes for the returned pieces
      Returns:
        a list of lists chopping the original iterator elements into pieces determined by chopSizes
      Since:
        2.5.2

    - #### public List collect(Closure transform)

      Iterates through this Iterator transforming each item into a new value using the `transform` closure, returning a list of transformed values.

      Parameters:
        `transform` - the closure used to transform each item
      Returns:
        a List of the transformed values
      Since:
        2.5.0

    - #### public Collection collect(Collection collector, Closure transform)

      Iterates through this Iterator transforming each item into a new value using the `transform` closure and adding it to the supplied `collector`.

      Parameters:
        `collector` - the Collection to which the transformed values are added
        `transform` - the closure used to transform each item
      Returns:
        the collector with all transformed values added to it
      Since:
        2.5.0

    - #### public Map collectEntries()

      A variant of collectEntries for Iterators using the identity closure as the transform.

      Returns:
        a Map of the transformed entries
      Since:
        1.8.7
      See Also:
        Iterable#collectEntries()

    - #### public Map collectEntries(Closure transform)

      A variant of collectEntries for Iterators.

      Parameters:
        `transform` - the closure used for transforming, which has an item from self as the parameter and should return a Map.Entry, a Map or a two-element list containing the resulting key and value
      Returns:
        a Map of the transformed entries
      Since:
        1.8.7
      See Also:
        Iterable#collectEntries(Closure)

    - #### public Map collectEntries(Map collector)

      A variant of collectEntries for Iterators using the identity closure as the transform and a supplied map as the destination of transformed entries.

      Parameters:
        `collector` - the Map into which the transformed entries are put
      Returns:
        the collector with all transformed values added to it
      Since:
        1.8.7
      See Also:
        Iterable#collectEntries(Map)

    - #### public Map collectEntries(Map collector, Closure transform)

      A variant of collectEntries for Iterators using a supplied map as the destination of transformed entries.

      Parameters:
        `collector` - the Map into which the transformed entries are put
        `transform` - the closure used for transforming, which has an item from self as the parameter and should return a Map.Entry, a Map or a two-element list containing the resulting key and value
      Returns:
        the collector with all transformed values added to it
      Since:
        1.8.7

    - #### public List collectMany(Closure projection)

      Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.

          def numsIter = [1, 2, 3, 4, 5, 6].iterator()
          def squaresAndCubesOfEvens = numsIter.collectMany{ it % 2 ? [] : [it**2, it**3] }
          assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]

      Parameters:
        `projection` - a projecting Closure returning a collection of items
      Returns:
        a list created from the projected collections concatenated (flattened) together
      Since:
        1.8.1
      See Also:
        Iterator#collectMany(Collection, groovy.lang.Closure)

    - #### public Collection collectMany(Collection collector, Closure projection)

      Projects each item from a source iterator to a collection and concatenates (flattens) the resulting collections into a single list.

          def numsIter = [1, 2, 3, 4, 5, 6].iterator()
          def squaresAndCubesOfEvens = numsIter.collectMany{ it % 2 ? [] : [it**2, it**3] }
          assert squaresAndCubesOfEvens == [4, 8, 16, 64, 36, 216]

      Parameters:
        `collector` - an initial collection to add the projected items to
        `projection` - a projecting Closure returning a collection of items
      Returns:
        the collector with the projected collections concatenated (flattened) to it
      Since:
        1.8.1
      See Also:
        Iterator#sum(groovy.lang.Closure)

    - #### public Number count(Closure closure)

      Counts the number of occurrences which satisfy the given closure from the items within this Iterator. The iterator will become exhausted of elements after determining the count value.

      Example usage:

          assert [2,4,2,1,3,5,2,4,3].toSet().iterator().count{ it % 2 == 0 } == 2

      Parameters:
        `closure` - a closure condition
      Returns:
        the number of occurrences
      Since:
        1.8.0

    - #### public Number count(Object value)

      Counts the number of occurrences of the given value from the items within this Iterator. Comparison is done using Groovy's == operator (using `compareTo(value) == 0` or `equals(value)` ). The iterator will become exhausted of elements after determining the count value.

      Parameters:
        `value` - the value being searched for
      Returns:
        the number of occurrences
      Since:
        1.5.0

    - #### public Map countBy(Closure closure)

      Sorts all iterator items into groups determined by the supplied mapping closure and counts the group size. The closure should return the key that each item should be grouped by. The returned Map will have an entry for each distinct key returned from the closure, with each value being the frequency of items occurring for that group.

      Example usage:

          assert [1,2,2,2,3].toSet().iterator().countBy{ it % 2 } == [1:2, 0:1]

      Parameters:
        `closure` - a closure mapping items to the frequency keys
      Returns:
        a new Map grouped by keys with frequency counts
      Since:
        1.8.0

    - #### public Iterator drop(int num)

      Drops the given number of elements from the head of this iterator if they are available. The original iterator is stepped along by `num` elements.

          def iteratorCompare( Iterator a, List b ) {
              a.collect { it } == b
          }
          def iter = [ 1, 2, 3, 4, 5 ].listIterator()
          assert iteratorCompare( iter.drop( 0 ), [ 1, 2, 3, 4, 5 ] )
          iter = [ 1, 2, 3, 4, 5 ].listIterator()
          assert iteratorCompare( iter.drop( 2 ), [ 3, 4, 5 ] )
          iter = [ 1, 2, 3, 4, 5 ].listIterator()
          assert iteratorCompare( iter.drop( 5 ), [] )

      Parameters:
        `num` - the number of elements to drop from this iterator
      Returns:
        The iterator stepped along by `num` elements if they exist.
      Since:
        1.8.1

    - #### public Iterator dropRight(int num)

      Drops the given number of elements from the tail of this Iterator.

          def getObliterator() { "obliter8".iterator() }
          assert obliterator.dropRight(-1).toList() == ['o', 'b', 'l', 'i', 't', 'e', 'r', '8']
          assert obliterator.dropRight(0).toList() == ['o', 'b', 'l', 'i', 't', 'e', 'r', '8']
          assert obliterator.dropRight(1).toList() == ['o', 'b', 'l', 'i', 't', 'e', 'r']
          assert obliterator.dropRight(4).toList() == ['o', 'b', 'l', 'i']
          assert obliterator.dropRight(7).toList() == ['o']
          assert obliterator.dropRight(8).toList() == []
          assert obliterator.dropRight(9).toList() == []

      Parameters:
        `num` - the number of elements to drop
      Returns:
        an Iterator consisting of all the elements of this Iterator minus the last `num` elements, or an empty Iterator if it has less then `num` elements.
      Since:
        2.4.0

    - #### public Iterator dropWhile(Closure condition)

      Creates an Iterator that returns a suffix of the elements from an original Iterator. As many elements as possible are dropped from the front of the original Iterator such that calling the given closure condition evaluates to true when passed each of the dropped elements.

          def a = 0
          def iter = [ hasNext:{ a < 10 }, next:{ a++ } ] as Iterator
          assert [].iterator().dropWhile{ it < 3 }.toList() == []
          assert [1, 2, 3, 4, 5].iterator().dropWhile{ it < 3 }.toList() == [ 3, 4, 5 ]
          assert iter.dropWhile{ it < 5 }.toList() == [ 5, 6, 7, 8, 9 ]

      Parameters:
        `condition` - the closure that must evaluate to true to continue dropping elements
      Returns:
        the shortest suffix of elements from the given Iterator such that the given closure condition evaluates to true for each element dropped from the front of the Iterator
      Since:
        1.8.7

    - #### public Iterator each(Closure closure)

      Iterates through an Iterator, passing each item to the given closure.

      Parameters:
        `closure` - the closure applied on each element found
      Returns:
        the self Iterator
      Since:
        2.4.0

    - #### public Iterator eachWithIndex(Closure closure)

      Iterates through an iterator type, passing each item and the item's index (a counter starting at zero) to the given closure.

      Parameters:
        `closure` - a Closure to operate on each item
      Returns:
        the self Iterator (now exhausted)
      Since:
        2.3.0

    - #### public boolean every(Closure predicate)

      Used to determine if the given predicate closure is valid (i.e. returns `true` for all items in this iterator). A simple example for a list:

          def list = [3,4,5]
          def greaterThanTwo = list.iterator().every { it > 2 }

      Parameters:
        `predicate` - the closure predicate used for matching
      Returns:
        true if every iteration of the object matches the closure predicate
      Since:
        2.3.0

    - #### public int findIndexOf(Closure condition)

      Iterates over the elements of an Iterator and returns the index of the first item that satisfies the condition specified by the closure.

      Parameters:
        `condition` - the matching condition
      Returns:
        an integer that is the index of the first matched object or -1 if no match was found
      Since:
        2.5.0

    - #### public int findIndexOf(int startIndex, Closure condition)

      Iterates over the elements of an Iterator, starting from a specified startIndex, and returns the index of the first item that satisfies the condition specified by the closure.

      Parameters:
        `startIndex` - start matching from this index
        `condition` - the matching condition
      Returns:
        an integer that is the index of the first matched object or -1 if no match was found
      Since:
        2.5.0

    - #### public List findIndexValues(Closure condition)

      Iterates over the elements of an Iterator and returns the index values of the items that match the condition specified in the closure.

      Parameters:
        `condition` - the matching condition
      Returns:
        a list of numbers corresponding to the index values of all matched objects
      Since:
        2.5.0

    - #### public List findIndexValues(Number startIndex, Closure condition)

      Iterates over the elements of an Iterator, starting from a specified startIndex, and returns the index values of the items that match the condition specified in the closure.

      Parameters:
        `startIndex` - start matching from this index
        `condition` - the matching condition
      Returns:
        a list of numbers corresponding to the index values of all matched objects
      Since:
        2.5.0

    - #### public int findLastIndexOf(Closure condition)

      Iterates over the elements of an Iterator and returns the index of the last item that matches the condition specified in the closure.

      Parameters:
        `condition` - the matching condition
      Returns:
        an integer that is the index of the last matched object or -1 if no match was found
      Since:
        2.5.0

    - #### public int findLastIndexOf(int startIndex, Closure condition)

      Iterates over the elements of an Iterator, starting from a specified startIndex, and returns the index of the last item that matches the condition specified in the closure.

      Parameters:
        `startIndex` - start matching from this index
        `condition` - the matching condition
      Returns:
        an integer that is the index of the last matched object or -1 if no match was found
      Since:
        2.5.0

    - #### public Object findResult(Closure condition)

      Iterates through the Iterator calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. If all results are null, null is returned.

      Parameters:
        `condition` - a closure that returns a non-null value to indicate that processing should stop and the value should be returned
      Returns:
        the first non-null result from calling the closure, or null
      Since:
        2.5.0

    - #### public Object findResult(Object defaultResult, Closure condition)

      Iterates through the Iterator calling the given closure condition for each item but stopping once the first non-null result is found and returning that result. If all are null, the defaultResult is returned.

      Examples:

          def iter = [1,2,3].iterator()
          assert "Found 2" == iter.findResult("default") { it > 1 ? "Found $it" : null }
          assert "default" == iter.findResult("default") { it > 3 ? "Found $it" : null }

      Parameters:
        `defaultResult` - an Object that should be returned if all closure results are null
        `condition` - a closure that returns a non-null value to indicate that processing should stop and the value should be returned
      Returns:
        the first non-null result from calling the closure, or the defaultValue
      Since:
        2.5.0

    - #### public Collection findResults(Closure filteringTransform)

      Iterates through the Iterator transforming items using the supplied closure and collecting any non-null results.

      Parameters:
        `filteringTransform` - a Closure that should return either a non-null transformed value or null for items which should be discarded
      Returns:
        the list of non-null transformed values
      Since:
        2.5.0

    - #### public Object getAt(int idx)

      Support the subscript operator for an Iterator. The iterator will be partially exhausted up until the idx entry after returning if a +ve or 0 idx is used, or fully exhausted if a -ve idx is used or no corresponding entry was found. Typical usage:

          def iter = [2, "a", 5.3].iterator()
          assert iter[1] == "a"

      A more elaborate example:

          def items = [2, "a", 5.3]
          def iter = items.iterator()
          assert iter[-1] == 5.3
          // iter exhausted, so reset
          iter = items.iterator()
          assert iter[1] == "a"
          // iter partially exhausted so now idx starts after "a"
          assert iter[0] == 5.3

      Parameters:
        `idx` - an index value (-self.size() <= idx < self.size())
      Returns:
        the value at the given index (after normalisation) or null if no corresponding value was found
      Since:
        1.7.2

    - #### public Iterator indexed()

      Zips an iterator with indices in (index, value) order.

      Example usage:

          assert [[0, "a"], [1, "b"]] == ["a", "b"].iterator().indexed().collect{ tuple -> [tuple.first, tuple.second] }
          assert ["0: a", "1: b"] == ["a", "b"].iterator().indexed().collect { idx, str -> "$idx: $str" }.toList()

      Returns:
        a zipped iterator with indices
      Since:
        2.4.0
      See Also:
        Iterator#withIndex()

    - #### public Iterator indexed(int offset)

      Zips an iterator with indices in (index, value) order.

      Example usage:

          assert [[5, "a"], [6, "b"]] == ["a", "b"].iterator().indexed(5).toList()
          assert ["a: 1", "b: 2"] == ["a", "b"].iterator().indexed(1).collect { idx, str -> "$str: $idx" }.toList()

      Parameters:
        `offset` - an index to start from
      Returns:
        a zipped iterator with indices
      Since:
        2.4.0
      See Also:
        Iterator#withIndex(int)

    - #### public Iterator init()

      Returns an Iterator containing all of the items from this iterator except the last one.

          def iter = [3, 4, 2].listIterator()
          def result = iter.init()
          assert result.toList() == [3, 4]

      Returns:
        an Iterator without the last element from the original Iterator
      Since:
        2.4.0

    - #### public Object inject(Object initialValue, Closure closure)

      Iterates through the given Iterator, passing in the initial value to the closure along with the first item. The result is passed back (injected) into the closure along with the second item. The new result is injected back into the closure along with the third item and so on until the Iterator has been expired of values. Also known as foldLeft in functional parlance.

      Parameters:
        `initialValue` - some initial value
        `closure` - a closure
      Returns:
        the result of the last closure call
      Since:
        1.5.0
      See Also:
        Collection#inject(Object, Closure)

    - #### public Iterator iterator()

      An identity function for iterators, supporting 'duck-typing' when trying to get an iterator for each object within a collection, some of which may already be iterators.

      Returns:
        itself
      Since:
        1.5.0

    - #### public String join(String separator)

      Concatenates the `toString()` representation of each item from the iterator, with the given String as a separator between each item. The iterator will become exhausted of elements after determining the resulting conjoined value.

      Parameters:
        `separator` - a String separator
      Returns:
        the joined String
      Since:
        1.5.5

    - #### public Object max()

      Adds max() method to Iterator objects. The iterator will become exhausted of elements after determining the maximum value.

      Returns:
        the maximum value
      Since:
        1.5.5

    - #### public Object max(Closure closure)

      Selects the maximum value found from the Iterator using the closure to determine the correct ordering. The iterator will become exhausted of elements after this operation.

      If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.

      Parameters:
        `closure` - a Closure used to determine the correct ordering
      Returns:
        the maximum value
      Since:
        1.5.5

    - #### public Object max(Comparator comparator)

      Selects the maximum value found from the Iterator using the given comparator.

      Parameters:
        `comparator` - a Comparator
      Returns:
        the maximum value
      Since:
        1.5.5

    - #### public Object min()

      Adds min() method to Iterator objects. The iterator will become exhausted of elements after determining the minimum value.

      Returns:
        the minimum value
      Since:
        1.5.5
      See Also:
        Iterable#min()

    - #### public Object min(Closure closure)

      Selects the minimum value found from the Iterator using the closure to determine the correct ordering. The iterator will become exhausted of elements after this operation.

      If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.

      Parameters:
        `closure` - a Closure used to determine the correct ordering
      Returns:
        the minimum value
      Since:
        1.5.5

    - #### public Object min(Comparator comparator)

      Selects the minimum value found from the Iterator using the given comparator.

      Parameters:
        `comparator` - a Comparator
      Returns:
        the minimum value
      Since:
        1.5.5

    - #### public Iterator reverse()

      Reverses the iterator. The original iterator will become exhausted of elements after determining the reversed values. A new iterator for iterating through the reversed values is returned.

      Returns:
        a reversed Iterator
      Since:
        1.5.5

    - #### public int size()

      Provide the standard Groovy `size()` method for `Iterator`. The iterator will become exhausted of elements after determining the size value.

      Returns:
        the length of the Iterator
      Since:
        1.5.5

    - #### public Iterator sort()

      Sorts the given iterator items into a sorted iterator. The items are assumed to be comparable. The original iterator will become exhausted of elements after completing this method call. A new iterator is produced that traverses the items in sorted order.

      Returns:
        the sorted items as an Iterator
      Since:
        1.5.5

    - #### public Iterator sort(Closure closure)

      Sorts the given iterator items into a sorted iterator using the Closure to determine the correct ordering. The original iterator will be fully processed after the method call.

      If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.

      Parameters:
        `closure` - a Closure used to determine the correct ordering
      Returns:
        the sorted items as an Iterator
      Since:
        1.5.5

    - #### public Iterator sort(Comparator comparator)

      Sorts the given iterator items into a sorted iterator using the comparator. The original iterator will become exhausted of elements after completing this method call. A new iterator is produced that traverses the items in sorted order.

      Parameters:
        `comparator` - a Comparator used for comparing items
      Returns:
        the sorted items as an Iterator
      Since:
        1.5.5

    - #### public Stream stream()

      Returns a sequential Stream with the specified element(s) as its source.

          [].iterator().stream().toList().isEmpty()
          ['one', 'two'].iterator().stream().toList() == ['one', 'two']

      Since:
        3.0.0

    - #### public Object sum()

      Sums the items from an Iterator. This is equivalent to invoking the "plus" method on all items from the Iterator. The iterator will become exhausted of elements after determining the sum value.

      Returns:
        The sum of all of the items
      Since:
        1.5.5

    - #### public Object sum(Closure closure)

      Sums the result of applying a closure to each item returned from an iterator. `iter.sum(closure)` is equivalent to: `iter.collect(closure).sum()`. The iterator will become exhausted of elements after determining the sum value.

      Parameters:
        `closure` - a single parameter closure that returns a (typically) numeric value.
      Returns:
        The sum of the values returned by applying the closure to each item from the Iterator.
      Since:
        1.7.1

    - #### public Object sum(Object initialValue)

      Sums the items from an Iterator, adding the result to some initial value. This is equivalent to invoking the "plus" method on all items from the Iterator. The iterator will become exhausted of elements after determining the sum value.

      Parameters:
        `initialValue` - the items in the collection will be summed to this initial value
      Returns:
        The sum of all of the items
      Since:
        1.5.5

    - #### public Object sum(Object initialValue, Closure closure)

      Sums the result of applying a closure to each item of an Iterator to some initial value. `iter.sum(initVal, closure)` is equivalent to: `iter.collect(closure).sum(initVal)`. The iterator will become exhausted of elements after determining the sum value.

      Parameters:
        `closure` - a single parameter closure that returns a (typically) numeric value.
        `initialValue` - the closure results will be summed to this initial value
      Returns:
        The sum of the values returned by applying the closure to each item from the Iterator.
      Since:
        1.7.1

    - #### public Iterator tail()

      Returns the original iterator after throwing away the first element.

      Returns:
        the iterator without its first element
      Since:
        1.8.1

    - #### public Iterator take(int num)

      Returns an iterator of up to the first `num` elements from this iterator. The original iterator is stepped along by `num` elements.

          def a = 0
          def iter = [ hasNext:{ true }, next:{ a++ } ] as Iterator
          def iteratorCompare( Iterator a, List b ) {
              a.collect { it } == b
          }
          assert iteratorCompare( iter.take( 0 ), [] )
          assert iteratorCompare( iter.take( 2 ), [ 0, 1 ] )
          assert iteratorCompare( iter.take( 5 ), [ 2, 3, 4, 5, 6 ] )

      Parameters:
        `num` - the number of elements to take from this iterator
      Returns:
        an iterator consisting of up to the first `num` elements of this iterator.
      Since:
        1.8.1

    - #### public Iterator takeWhile(Closure condition)

      Returns the longest prefix of elements in this iterator where each element passed to the given condition closure evaluates to true.

          def a = 0
          def iter = [ hasNext:{ true }, next:{ a++ } ] as Iterator

          assert [].iterator().takeWhile{ it < 3 }.toList() == []
          assert [1, 2, 3, 4, 5].iterator().takeWhile{ it < 3 }.toList() == [ 1, 2 ]
          assert iter.takeWhile{ it < 5 }.toList() == [ 0, 1, 2, 3, 4 ]

      Parameters:
        `condition` - the closure that must evaluate to true to continue taking elements
      Returns:
        a prefix of elements in the given iterator where each element passed to the given closure evaluates to true
      Since:
        1.8.7

    - #### public List toList()

      Convert an iterator to a List. The iterator will become exhausted of elements after making this conversion.

      Returns:
        a List
      Since:
        1.5.0

    - #### public Set toSet()

      Convert an iterator to a Set. The iterator will become exhausted of elements after making this conversion.

      Returns:
        a Set
      Since:
        1.8.0

    - #### public Iterator toSorted()

      Sorts the Iterator. Assumes that the Iterator elements are comparable and uses a NumberAwareComparator to determine the resulting order. `NumberAwareComparator` has special treatment for numbers but otherwise uses the natural ordering of the Iterator elements. A new iterator is produced that traverses the items in sorted order.

      Returns:
        the sorted items as an Iterator
      Since:
        2.4.0
      See Also:
        Iterator#toSorted(Comparator)

    - #### public Iterator toSorted(Closure closure)

      Sorts the given iterator items into a sorted iterator using the Closure to determine the correct ordering. The original iterator will be fully processed after the method call.

      If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.

      Parameters:
        `closure` - a Closure used to determine the correct ordering
      Returns:
        the sorted items as an Iterator
      Since:
        2.4.0
      See Also:
        Iterator#toSorted(Comparator)

    - #### public Iterator toSorted(Comparator comparator)

      Sorts the given iterator items using the comparator. The original iterator will become exhausted of elements after completing this method call. A new iterator is produced that traverses the items in sorted order.

      Parameters:
        `comparator` - a Comparator used for comparing items
      Returns:
        the sorted items as an Iterator
      Since:
        2.4.0

    - #### public Iterator toUnique()

      Returns an iterator equivalent to this iterator with all duplicated items removed by using the natural ordering of the items.

      Returns:
        an Iterator with no duplicate items
      Since:
        2.4.0

    - #### public Iterator toUnique(Closure condition)

      Returns an iterator equivalent to this iterator but with all duplicated items removed where duplicate (equal) items are deduced by calling the supplied Closure condition.

      If the supplied Closure takes a single parameter, the argument passed will be each element, and the closure should return a value used for comparison (either using Comparable#compareTo(java.lang.Object) or Object#equals(java.lang.Object)). If the closure takes two parameters, two items from the Iterator will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).

          def items = "Hello".toList() + [null, null] + "there".toList()
          def toLower = { it == null ? null : it.toLowerCase() }
          def noDups = items.iterator().toUnique(toLower).toList()
          assert noDups == ['H', 'e', 'l', 'o', null, 't', 'r']

          assert [1,4] == [1,3,4,5].toUnique { it % 2 }

          assert [2,3,4] == [2,3,3,4].toUnique { a, b -> a <=> b }

      Parameters:
        `condition` - a Closure used to determine unique items
      Returns:
        an Iterator with no duplicate items
      Since:
        2.4.0

    - #### public Iterator toUnique(Comparator comparator)

      Returns an iterator equivalent to this iterator with all duplicated items removed by using the supplied comparator.

      Parameters:
        `comparator` - a Comparator used to determine unique (equal) items If `null`, the Comparable natural ordering of the elements will be used.
      Returns:
        an Iterator with no duplicate items
      Since:
        2.4.0

    - #### public Iterator unique()

      Returns an iterator equivalent to this iterator with all duplicated items removed by using Groovy's default number-aware comparator. The original iterator will become exhausted of elements after determining the unique values. A new iterator for the unique values will be returned.

      Returns:
        a new Iterator of the unique items from the original iterator
      Since:
        1.5.5

    - #### public Iterator unique(Closure condition)

      Returns an iterator equivalent to this iterator but with all duplicated items removed by using a Closure to determine duplicate (equal) items. The original iterator will be fully processed after the call.

      If the closure takes a single parameter, the argument passed will be each element, and the closure should return a value used for comparison (either using Comparable#compareTo(java.lang.Object) or Object#equals(java.lang.Object)). If the closure takes two parameters, two items from the Iterator will be passed as arguments, and the closure should return an int value (with 0 indicating the items are not unique).

      Parameters:
        `condition` - a Closure used to determine unique items
      Returns:
        the modified Iterator
      Since:
        1.5.5

    - #### public Iterator unique(Comparator comparator)

      Returns an iterator equivalent to this iterator with all duplicated items removed by using the supplied comparator. The original iterator will be exhausted upon returning.

      Parameters:
        `comparator` - a Comparator
      Returns:
        the modified Iterator
      Since:
        1.5.5

    - #### public Iterator withIndex()

      Zips an iterator with indices in (value, index) order.

      Example usage:

          assert [["a", 0], ["b", 1]] == ["a", "b"].iterator().withIndex().toList()
          assert ["0: a", "1: b"] == ["a", "b"].iterator().withIndex().collect { str, idx -> "$idx: $str" }.toList()

      Returns:
        a zipped iterator with indices
      Since:
        2.4.0
      See Also:
        Iterator#indexed()

    - #### public Iterator withIndex(int offset)

      Zips an iterator with indices in (value, index) order.

      Example usage:

          assert [["a", 5], ["b", 6]] == ["a", "b"].iterator().withIndex(5).toList()
          assert ["1: a", "2: b"] == ["a", "b"].iterator().withIndex(1).collect { str, idx -> "$idx: $str" }.toList()

      Parameters:
        `offset` - an index to start from
      Returns:
        a zipped iterator with indices
      Since:
        2.4.0
      See Also:
        Iterator#indexed(int)