HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java 8 / Java – Internal vs. External Iteration

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?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Sunguk Keem

    December 15, 2017

    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()));
        }
    }
    
  2. Himansu

    September 30, 2016

    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);
    }
    }

    • Jakub

      December 8, 2017

      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.

  3. sri

    November 8, 2014

    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

    • Lokesh Gupta

      November 11, 2014

      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);
            }
         }
      }
      
  4. bryan jacobs

    April 11, 2014

    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.

Comments are closed on this article!

Search Tutorials

Java 8 Tutorial

  • Java 8 Features
  • Java 8 forEach
  • Java 8 Stream
  • Java 8 Boxed Stream
  • Java 8 Lambda Expression
  • Java 8 Functional Interface
  • Java 8 Method Reference
  • Java 8 Default Method
  • Java 8 Optional
  • Java 8 Predicate
  • Java 8 Regex as Predicate
  • Java 8 Date Time
  • Java 8 Iterate Directory
  • Java 8 Read File
  • Java 8 Write to File
  • Java 8 WatchService
  • Java 8 String to Date
  • Java 8 Difference Between Dates
  • Java 8 Join Array
  • Java 8 Join String
  • Java 8 Exact Arithmetic
  • Java 8 Comparator
  • Java 8 Base64
  • Java 8 SecureRandom
  • Internal vs External Iteration

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)