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 !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

6 thoughts on “Java – Internal vs External Iteration”

  1. The internal-iteration equivalent example doesn’t do the same. You can use the following to do the same.

    public class IterationExamples {
        public static void main(String[] args){
            List<String> alphabets = Arrays.asList(new String[]{"a","b","b","d"});
             
            alphabets.forEach(l -> System.out.println(l.toUpperCase()));
        }
    }
    
    Reply
  2. Hi Lokesh,

    Apart of Internal Iterator we can also use Consumer i.e.

    alphabets.forEach(new Consumer() {
    @Override
    public void accept(String s) {
    s.toUpperCase();
    }
    });

    or
    alphabets.forEach(new ReuseConsumer());

    class ReuseConsumer implements Consumer {

    @Override
    public void accept(String s) {
    System.out.println(s);
    }
    }

    Reply
    • There is no reason to move one-liner to >5 lines of code, when it comes to Functional Interfaces. You are right, but it is the outcome of lambdas being used. If You want to add something to that interface – statics, defaults, sure go for it.

      Reply
  3. Hi Guptha,

    Create a vector add elements to the vector .Iterate through vector using enumaration object.Write a code to copy all the elements of vector to the array and then iterate through enhanced for loop and print it.. Everything should be in collections only?

    Can anyone please help me to do ?

    Thanks Advacnce

    Reply
    • Will it solve your exercise?

      public class VectorExample
      {
         public static void main(String[] args)
         {
            Vector&lt;String&gt; names = new Vector&lt;String&gt;();
            names.add(&quot;Lokesh&quot;);
            names.add(&quot;Sri&quot;);
            names.add(&quot;John&quot;);
            
            //Iterate through Enumeration
            Enumeration&lt;String &gt; itr = names.elements();
            while(itr.hasMoreElements()){
               System.out.println(itr.nextElement());
            }
            
            //Copy in Array and Iterate
            String[] namesArr = new String[names.size()];
            
            names.toArray(namesArr);
            
            for(String name : namesArr){
               System.out.println(name);
            }
         }
      }
      
      Reply
  4. If Java could more quickly include some of the ruby idioms perhaps the language will keep relevant. JavaScript is so busy trying to build a server-side platform and Java is already there. I would love to see the language continue to evolve to essentially look like scala. Then we would have all the benefits of java tooling/platform with a modern language.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.