Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Iterator vs Foreach In Java
Next article icon

Iterator vs Foreach In Java

Last Updated : 15 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Background : 
Iterator is an interface provided by collection framework to traverse a collection and for a sequential access of items in the collection. 
 

        // Iterating over collection 'c' using iterator     for (Iterator i = c.iterator(); i.hasNext(); )          System.out.println(i.next());


For eachloop is meant for traversing items in a collection. 
 

   // Iterating over collection 'c' using for-each      for (Element e: c)         System.out.println(e);


We read the ':' used in for-each loop as “in”. So loop reads as “for each element e in elements”, here elements is the collection which stores Element type items.


Note : In Java 8 using lambda expressions we can simply replace for-each loop with 
 

elements.forEach (e -> System.out.println(e) );


Difference between the two traversals 
In for-each loop, we can’t modify collection, it will throw a ConcurrentModificationException on the other hand with iterator we can modify collection. 
 

Modifying a collection simply means removing an element or changing content of an item stored in the collection. This occurs because for-each loop implicitly creates an iterator but it is not exposed to the user thus we can’t modify the items in the collections.


When to use which traversal? 
 

  • If we have to modify collection, we can use Iterator. 
     
  • While using nested for loops it is better to use for-each loop, consider the below code for better understanding.


 

Java
// Java program to demonstrate working of nested iterators // may not work as expected and throw exception. import java.util.*;  public class Main {     public static void main(String args[])     {         // Create a link list which stores integer elements         List<Integer> l = new LinkedList<Integer>();          // Now add elements to the Link List         l.add(2);         l.add(3);         l.add(4);          // Make another Link List which stores integer elements         List<Integer> s=new LinkedList<Integer>();         s.add(7);         s.add(8);         s.add(9);          // Iterator to iterate over a Link List         for (Iterator<Integer> itr1=l.iterator(); itr1.hasNext(); )         {             for (Iterator<Integer> itr2=s.iterator(); itr2.hasNext(); )             {                 if (itr1.next() < itr2.next())                 {                     System.out.println(itr1.next());                 }             }         }     } } 

Output: 
 

Exception in thread "main" java.util.NoSuchElementException        at java.util.LinkedList$ListItr.next(LinkedList.java:888)        at Main.main(Main.java:29)


The above code throws java.util.NoSuchElementException. 
 

In the above code we are calling the next() method again and again for itr1 (i.e., for List l). Now we are advancing the iterator without even checking if it has any more elements left in the collection(in the inner loop), thus we are advancing the iterator more than the number of elements in the collection which leads to NoSuchElementException.


 

for-each loops are tailor made for nested loops. Replace the iterator code with the below code.


 

Java
// Java program to demonstrate working of nested for-each import java.util.*; public class Main {     public static void main(String args[])     {         // Create a link list which stores integer elements         List<Integer> l=new LinkedList<Integer>();          // Now add elements to the Link List         l.add(2);         l.add(3);         l.add(4);          // Make another Link List which stores integer elements         List<Integer> s=new LinkedList<Integer>();         s.add(2);         s.add(4);         s.add(5);         s.add(6);          // Iterator to iterate over a Link List         for (int a:l)         {             for (int b:s)             {                 if (a<b)                     System.out.print(a + " ");             }         }     } } 

Output: 
 

  2 2 2 3 3 3 4 4


Performance Analysis 
 

Traversing a collection using for-each loops or iterators give the same performance. Here, by performance we mean the time complexity of both these traversals.


If you iterate using the old styled C for loop then we might increase the time complexity drastically.
// Here l is List ,it can be ArrayList /LinkedList and n is size of the List 
 

for (i=0;i<n;i++)     System.out.println(l.get(i));


 

Here if the list l is an ArrayList then we can access it in O(1) time since it is allocated contiguous memory blocks (just like an array) i.e random access is possible. But if the collection is LinkedList, then random access is not possible since it is not allocated contiguous memory blocks, so in order to access a element we will have to traverse the link list till you get to the required index, thus the time taken in worst case to access an element will be O(n).


 

Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.


Related Articles: 
Iterators in Java 
Retrieving Elements from Collection in Java (For-each, Iterator, ListIterator & EnumerationIterator)
References: 
https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html 
https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html 
https://stackoverflow.com/questions/2113216/which-is-more-efficient-a-for-each-loop-or-an-iterator
 


 


 


Next Article
Iterator vs Foreach In Java

C

Chirag Agarwal
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Iterator vs Collection in Java
    Iterator and Collection, both has helped and comforted the programmers at many a times. But their usage and application has a very wide difference. 1. Iterator Declaration public interface Iterator Type Parameters: E - the type of elements returned by this iteratorIterators are used in Collection fr
    3 min read
    Iterable forEach() Method in Java
    In Java, the foreach() method is the default method in the Iterable interface. It provides a simple way to iterate over all elements of an Iterable such as List, Set, etc. using a lambda expression or method reference. Example 1: This example demonstrates iterating over a List using an Iterator to p
    3 min read
    How to use Iterator in Java?
    'Iterator' is an interface which belongs to collection framework. It allows us to traverse the collection, access the data element and remove the data elements of the collection. java.util package has public interface Iterator and contains three methods: boolean hasNext(): It returns true if Iterato
    3 min read
    IntStream forEach() method in Java
    The IntStream forEach() method in Java is a terminal operation that performs a given action on each element of the stream. It is commonly used to iterate through primitive int values in a functional style introduced in Java 8.Syntax of IntStream forEach() Methodvoid forEach(IntConsumer action)Parame
    2 min read
    Deque iterator() method in Java
    The iterator() method of Deque Interface returns an iterator over the elements in this deque in a proper sequence. The elements will be returned in order from first (head) to last (tail). The returned iterator is a “weakly consistent” iterator. Syntax: Iterator iterator() Parameters: This method doe
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences