External Iteration and Internal Iteration In Java

External Iteration :

    While working with Collections, you might have gotten a situation, where you want to iterate over a collection and perform some operation on each element. For example, if we have a list of strings, and we want to count the number of Strings whose length is greater than 5. We would write the code as like below.
   List strList = Arrays.asList("www","speakingcs","com","posts","java 8");
   int count = 0; 
   for(String str : strList) {
     if(str.length > 5) {
If you observe the above approach, you can find several problems associated with it.
1. It involves a lot of boilerplate code that needs to written every time you want to iterate over the collection.
2. It's difficult to write a parallel version of this for loop.
3. This code doesn't fluently convey the intent of the programmer. To understand this we must read entire body of the for loop. This becomes burden when you have a large code base with full of for loops.

Under the hood, this for loop calls the iterator method, which return a new iterator object. This is called as external iteration. The iteration then proceeds by explicitly calling the hasNext() and next() methods on the iterator object.  The expanded code looks like this.
   Iterator itr = strList.iterator();
   String str = "";
   count = 0;
   while(itr.hasNext()) {
        str = itr.next();
 if(str.length() > 5) {
     count ++;
This is the traditional approach and is serial in nature.

Internal Iteration :

To overcome the above specified problems, the alternative approach is Internal Iteration. The rewritten code using java 8 is,
   long count = strList.stream().filter(s1 -> s1.length()>5).count();
In the above code, the call to stream(), performs a similar role to the call iterator() in the previous all. Instead of returning an iterator to control the iteration, it returns the equivalent interface in the Internal Iteration world i.e Stream.

The operations filter and count corresponds to Stream interface. filter(), filters the stream elements based on a condition, here the condition is length of the string should be greater than 5. This condition will be applied to all the elements of the stream,  one at a time. Here we are not iterating the elements externally, every thing will be handled by methods of Stream interface.

The above code is concise and simple. The five lines of code is reduced to a single line with the help of internal iteration.  The code is also became easy to read and understand.

This is how internal iteration works. If you want to know more about streams you can find a post at streams in java 8