The Java platform includes a variety of ways to iterate over a collection of objects, including new options based on features introduced in Java 8. In this article John Moore revisits the Iterator design pattern with attention to the difference between active and passive iterators. Learn how Java 8's forEach() method and features of the Stream API can help you fine-tune and parallelize the behavior of your iterators, then conclude with some performance benchmarks that might surprise you.
Anytime you have a collection of things you will need some mechanism to systematically step though the items in that collection. As an everyday example, consider the television remote control, which lets us iterate over various television channels. Similarly, in the programming world, we need a mechanism to systematically step through a collection of software objects. The mechanism used for this purpose is known by various names, including index (for iterating over an array), cursor (for iterating over the results of a database query), enumeration (in early versions of Java), and iterator (in more recent versions of Java).