Java – Internal vs. External Iteration

External iteration

Till Java 7, the collections framework relied on the concept of external iteration, where a Collection provides, by implementing Iterable, a means to enumerate its elements i.e. Iterator, and clients use this to step sequentially through the elements of a collection. For example, if we wanted to get all strings in uppercase, we would write:

public class IterationExamples {
	public static void main(String[] args){
		List<String> alphabets = Arrays.asList(new String[]{"a","b","b","d"});
		
		for(String letter: alphabets){
			System.out.println(letter.toUpperCase());
		}
	}
}

OR we can write like this:

public class IterationExamples {
	public static void main(String[] args){
		List<String> alphabets = Arrays.asList(new String[]{"a","b","b","d"});
		
		Iterator<String> iterator = alphabets.listIterator();
		while(iterator.hasNext()){
			System.out.println(iterator.next().toUpperCase());
		}
	}
}

Above both code snippets are for external iteration. External iteration is straightforward enough, but it has several problems:

1) Java’s for-each loop/iterator is inherently sequential, and must process the elements in the order specified by the collection.
2) 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.

Internal iteration

Sometimes the strong guarantees of the for-each loop (sequential, in-order) are desirable, but often are just an disadvantage to performance. The alternative to external iteration is internal iteration, where instead of controlling the iteration, client let it handle by library and only provide the code which must be executed for all/some of data elements.

The internal-iteration equivalent of the previous example is:

public class IterationExamples {
	public static void main(String[] args){
		List<String> alphabets = Arrays.asList(new String[]{"a","b","b","d"});
		
		alphabets.forEach(l -> l.toUpperCase());
	}
}
Where external iteration mixes the “what” (uppercase) and the “how” (for loop/iterator), internal iteration lets the client to provide only the “what” but lets the library control the “how”. This offers several potential benefits: 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.

That’s all for regarding Internal vs. External Iteration.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

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 its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.