Internal vs. External Iteration in Java

Learn the difference between internal iteration and external iteration in Java with examples.

1. External Iteration

Till Java 7, the collections framework relied on the concept of external iteration where the 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 to UPPERCASE, we will 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 provide better performance by exploiting data reordering, 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. Instead of controlling the iteration, the client code lets iteration be handled by the library and only provides the code to be executed for all/some 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 needs only focus on stating the problem, not the details of how to solve it, and we can move complex optimization code into libraries where it can benefit all users.

Happy Learning !!

Comments

Subscribe
Notify of
guest
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

Dark Mode

Dark Mode