Java – Internal vs External Iteration

1. External Iteration

Till Java 7, the collections framework relied on the concept of external iteration where a Collection provides a means to enumerate its elements by implementing the Iterator interface.

The clients use the iterator to iterate, sequentially, through the collection items.

For example, we have a list of Strings and if we want to convert all strings in uppercase, we would write:

Iterator<String> iterator = alphabets.listIterator();

while(iterator.hasNext()){
    System.out.println(iterator.next().toUpperCase());
}

OR we can write like the above code with the help of for-each loop. Note that for-each loop internally uses the Iterator interface methods hasNext() and next().

List<String> alphabets = Arrays.asList(new String[]{"a", "b", "c", "d"});
 
for(String letter: alphabets){
    System.out.println(letter.toUpperCase());
}

Above both snippets are examples of external iteration.

External iteration is straightforward enough, but it has several problems:

  • Java’s for-each loop/iterator is inherently sequential, and must process the items in the order specified by the collection.
  • It limits the opportunity to manage the control flow, which might be able to provide better performance by exploiting reordering of the data, parallelism, short-circuiting, or laziness.

2. Internal Iteration

Sometimes the strong guarantees of the for-each loop (sequential, in-order) are desirable, but often are just a disadvantage to performance.

The alternative to external iteration is internal iteration where instead of controlling the iteration, the client code lets iteration handled by the library and only provides the code which must be executed for all/some of the items.

The Collection.forEach() and Stream.forEach() are examples of external iterations.

List<String> alphabets = Arrays.asList(new String[]{"a", "b", "c", "d"});
 
alphabets.forEach(a -> a.toUpperCase());

3. Conclusion

While the external iteration mixes the “what” (uppercase) and the “how” (for loop/iterator), the internal iteration lets the client provide only the “what” but lets the library control the “how”.

This offers several potential benefits, for example, client code can be clearer because it need only focus on stating the problem, not the details of how to go about solving it, and we can move complex optimization code into libraries where it can benefit all users.

Happy Learning !!

Leave a Reply

6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial