# Computer Science Design Patterns/Iterator

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

## Examples

In Java, the interface java.util.Iterator<E> is an implementation of the iterator pattern. That way, all the objects that implement the java.lang.Iterable<T> interface don't need a handy implementation of this pattern.

## Cost

This pattern has a cost. Only implement this pattern for an important amount of code. IDE refactoring can't help you much.

### Creation

This pattern has a cost to create.

### Maintenance

This pattern is easy to maintain.

### Removal

This pattern has a cost to remove too.

## Advises

* Put the iterator term in the name of the iterator class to indicate the use of the pattern to the other developers.

## Implementations

Java has the Iterator interface.
A simple example showing how to return integers between [start, end] using an Iterator
As of Java 5, objects implementing the Template:Javadoc:SE interface, which returns an Iterator from its only method, can be traversed using Java's foreach loop syntax. The Template:Javadoc:SE interface from the Java collections framework extends Iterable.
Here is another example in Java:
Two different usage examples:
JavaScript, as part of ECMAScript 6, supports the iterator pattern with any object that provides a next method, which returns an object with two specific properties: done and value. Here's an example that shows a reverse array iterator:
Most of the time, though, it is desirable to provide Iterator semantics on objects so that they can be iterated automatically via for...of loops. Some of JavaScript's built-in types such as Array, Map, or Set already define their own iteration behavior. The same effect can be achieved by defining an object's meta @@iterator method, also referred to by Symbol.iterator. This creates an Iterable object.
Here's an example of a range function that generates a list of values starting from start to end, exclusive, using a regular for loop to generate the numbers:
The iteration mechanism of built-in types, like strings, can also be manipulated:
.NET Framework has special interfaces that support a simple iteration: System.Collections.IEnumerator over a non-generic collection and System.Collections.Generic.IEnumerator<T> over a generic collection.
C# statement foreach is designed to easily iterate through the collection that implements System.Collections.IEnumerator and/or System.Collections.Generic.IEnumerator<T> interface. Since C# v2, foreach is also able to iterate through types that implement System.Collections.Generic.IEnumerable<T> and System.Collections.Generic.IEnumerator<T>
Example of using foreach statement:
Here is another example in C#:
PHP supports the iterator pattern via the Iterator interface, as part of the standard distribution. Objects that implement the interface can be iterated over with the foreach language construct.
Example of patterns using PHP:

#### Output

Another example: As a default behavior in PHP 5, using an object in a foreach structure will traverse all public values. Multiple Iterator classes are available with PHP to allow you to iterate through common lists, such as directories, XML structures and recursive arrays. It's possible to define your own Iterator classes by implementing the Iterator interface, which will override the default behavior. The Iterator interface definition:
These methods are all being used in a complete foreach( $object as $key=>$value ) sequence. The methods are executed in the following order:
According to Zend, the current method is called before and after the valid method.
In Perl, objects providing an iterator interface either overload the <> (iterator operator), or provide a hash or tied hash interface that can be iterated over with each. Both <> and each return undef when iteration is complete. Overloaded <> operator:
Iterating over a hash (or tied hash):
Python prescribes a syntax for iterators as part of the language itself, so that language keywords such as for work with what Python calls iterables. An iterable has an __iter__ method that returns an iterator object. The "iterator protocol" requires next return the next element or raise a StopIteration exception upon reaching the end of the sequence. Iterators also provide an __iter__ method returning themselves so that they can also be iterated over; e.g., using a for loop. Generators are available since 2.2.
In Python 3, next was renamed __next__.
In Python, iterators are objects that adhere to the iterator protocol. You can get an iterator from any sequence (i.e. collection: lists, tuples, dictionaries, sets, etc.) with the iter method. Another way to get an iterator is to create a generator, which is a kind of iterator. To get the next element from an iterator, you use the next method (Python 2) / next function (Python 3). When there are no more elements, it raises the StopIteration exception. To implement your own iterator, you just need an object that implements the next method (Python 2) / __next__ method (Python 3). Here are two use cases:
Raku provides APIs for iterators, as part of the language itself, for objects that can be iterated with for and related iteration constructs, like assignment to a Positional variable. An iterable must at least implement an iterator method that returns an iterator object. The "iterator protocol" requires the pull-one method to return the next element if possible, or return the sentinel value IterationEnd if no more values could be produced. The iteration APIs is provided by composing the Iterable role, Iterator, or both, and implementing the required methods.
To check if a type object or an object instance is iterable, the does method can be used:
The does method returns True if and only if the invocant conforms to the argument type.
Here's an example of a range subroutine that mimics Python's range function:
MATLAB supports both external and internal implicit iteration using either "native" arrays or cell arrays. In the case of external iteration where the onus is on the user to advance the traversal and request next elements, one can define a set of elements within an array storage structure and traverse the elements using the for-loop construct. For example,
traverses an array of integers using the for keyword. In the case of internal iteration where the user can supply an operation to the iterator to perform over every element of a collection, many built-in operators and MATLAB functions are overloaded to execute over every element of an array and return a corresponding output array implicitly. Furthermore, the arrayfun and cellfun functions can be leveraged for performing custom or user defined operations over "native" arrays and cell arrays respectively. For example,
defines a primary function simpleFun which implicitly applies custom subfunction myCustomFun to each element of an array using built-in function arrayfun.
Alternatively, it may be desirable to abstract the mechanisms of the array storage container from the user by defining a custom object-oriented MATLAB implementation of the Iterator Pattern. Such an implementation supporting external iteration is demonstrated in MATLAB Central File Exchange item Design Pattern: Iterator (Behavioural). This is written in the new class-definition syntax introduced with MATLAB software version 7.6 (R2008a)
and features a one-dimensional cell array realisation of the List Abstract Data Type (ADT) as the mechanism for storing a heterogeneous (in data type) set of elements. It provides the functionality for explicit forward List traversal with the hasNext, next and reset methods for use in a while-loop.

## References

* ↑ "Iterators and generators". Retrieved 18 March 2016.
* ↑ "C# foreach statement".
* ↑ "PHP: Iterator". Retrieved 23 June 2013.
* ↑ File handle objects implement this to provide line by line reading of their contents
* ↑ In Perl 5.12, arrays and tied arrays can be iterated over like hashes, with each
* ↑ "Python v2.7.1 documentation: The Python Standard Library: 5. Built-in Types". Retrieved 2 May 2011.
* ↑ "Raku documentation: role Iterable". Retrieved 9 December 2020.
* ↑ "Raku documentation: role Iterator". Retrieved 9 December 2020.
* ↑ "New Class-Definition Syntax Introduced with MATLAB Software Version 7.6". The MathWorks, Inc. March 2009. Retrieved September 22, 2009.