External iterators vs internal iterators

 253 total views,  2 views today

Let us see External iterators vs internal iterators.

In Java, there are two types of iterators : internal iterators and External iterators.

What is an iterator?

Iterators are mainly used for traversing a collection.E.g list or map.

What is an external iterator?

An external iterator is a program/developer controlled iterator. For example, for-loop or List Iterator. Programmers define the iteration logic to traverse through the collection. Hence it is handled externally in the code.

What is an internal iterator?

When the iteration is controlled internally by iterator then it is called internal iterator. For example, forEach in Java 8. Programmers will concentrate only on the business logic.

What is recommended iterator?

External iterators are recommend because it is less prone to error ,simple and readable.

External iterator example

public static void main(String[] args) {
        List<String> list  = new ArrayList<>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");
        
        //Traditional for-loop
        for(String item:list) {
            System.out.println(item);
        }
}

Internal iterator example

public static void main(String[] args) {
        List<String> list  = new ArrayList<>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");
        list.add("Item 4");
        
        //Iterate and print each element
        list.forEach(item -> System.out.println(item));
        
        list.forEach(item ->{
            if(item.equalsIgnoreCase("Item 1")) {
                System.out.println("I am Item 1");
            }
        });
}
    

If you would like to lean How to use forEach.

Refer official documentation.

Thanks for reading.Please provide your valuable feedback for this article.

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.