Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Iterator in Java: Understanding the Fundamentals of Java Iterator

Updated on 03 July, 2023

5.78K+ views
8 min read

While working in Java, you may have faced a situation where you need to cycle through all the elements of a collection. For example, you may wish to display the elements one by one or retrieve each of the elements. You can accomplish these tasks with ease by employing a Java iterator. And, this brings us to the question, what is an iterator in Java?

Check out our free courses to get an edge over the competition

What is an Iterator in Java?

An ‘iterator’ is an interface that belongs to the Java Collection framework. It facilitates traversing a collection, accessing data elements, and removing data elements from the collection. In simple terminology, a Java iterator allows one to cycle through a collection of elements. And, at the same time, it obtains or removes specific elements from the given collection. Java has three iterators, namely enumeration, iterator, and list iterator.

Check out upGrad’s Advanced Certification in Cloud Computing 

Read more: A Guide to Iterator Implementation in Java

Enumeration

Enumeration is a Java iterator interface that allows obtaining elements of the legacy collections like vector and hashtable. The enumeration interface is the first iterator in JDK 1.0, and the rest, more functional ones being included in JDK 1.2. Enumerations are also used for specifying the input streams to a SequenceInputStream. To create the enumeration object, the elements( ) method of the vector class needs to be adopted. There are two methods of the enumeration interface:

  • boolean hasMoreElements( ): It checks the availability of the next element.
  • Object nextElement( ): It returns the next element. 

Check out upGrad’s Advanced Certification in Cyber Security

Iterator

The iterator interface is universal, and hence, it can be applied to any collection object. By using this Java iterator, both reading and removal operations can be carried out. The interface is an improved version of enumeration with more straightforward method names and the additional function of removing elements from collections.

Since it is the only available cursor for the entire Collection framework, the iterator interface can be used whenever there is a need to enumerate the elements in interfaces like List, Set, Queue, and Deque. An iterator also works in all the implemented classes of the Map interface. Creation of the iterator object is done by calling the Iterator( ) method present in the collection interface.

The iterator interface declares three methods:

  • boolean hasNext( ): It returns true in the case there are more elements, or else, returns false.
  • Object next( ): It returns the next element. But, if there is no element next, it throws NoSuchElementException.
  • void remove( ): This method is for the removal of current element. It will throw IllegalStateException if remove( ) is called without first invoking the next ( ) method.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

List Iterator

The list iterator type of Java iterator is only applicable for classes like LinkedList and ArrayList that are implemented by List Collection. In contrast to the enumeration and iterator interfaces, the list iterator allows bi-directional iteration and can be used to enumerate the elements of a list. The list interface contains the listIterator( ) method which can be invoked for creating the list iterator object. The list iterator interface is an extension of the iterator interface.

In addition to the three methods present in the iterator, a list iterator contains six more methods. And, these are:

  • void add(Object obj): It adds an object to the list in front of the element which will be returned by the subsequent call to next( ).
  • boolean hasNext( ): It returns true in the case there is any next element. Else, it returns false.
  • boolean hasPrevious( ): It returns true in the case there is a previous element. Else, it returns false.
  • Object next( ): It returns the next element. But, if there is no element next, it throws NoSuchElementException.
  • int nextIndex( ): This method is for returning the index of the next element. It will return the size of the list in case there is no next element.
  • Object previous( ): It returns the previous element. But, if there is no previous element, it throws NoSuchElementException.
  • int previousIndex( ): This method is for returning the index of the previous element. It will return -1 in case there is no next element.
  • void remove( ): This method is for the removal of the current element. It will throw IllegalStateException if remove( ) is called without first invoking the next ( ) method.
  • void set(Object obj): It is for assigning an object to the current element. This is the element that is returned last by a call to either previous( ) or next( ).

Advantages of Iterator in Java

The different benefits of using an iterator in Java are as follows:

  • Useful for a Collection class
  • Can support READ as well as REMOVE operations
  • Universal Cursor for Collection API
  • Simple and easy method names

Limitations of Java Iterator

The different limitations of an iterator in Java are as follows:

  • It won’t support UPDATE and CREATE operations in CRUD. 
  • It only accommodates Forward direction iteration because it is unidirectional. 
  • Unlike Spliterator, it does not support parallel iterating elements. Therefore, you can only find support for sequential iteration. 
  • Unlike Spliterator, it does not accommodate better performance to iterate large data volumes. 

Methods of Iterator Interface in Java

The iterator interface can define the three key methods:

  • hasNext(): Returns true in case the iteration has more elements. 

public boolean hasNext();

  • next(): Returns the subsequent element in the iteration. If no more elements are present, it brings NoSuchElementException. 

public Object next();

  • remove(): Eliminates the succeeding element in the iteration. This method can be employed only once per call to next(). 

public void remove();

How to Iterate Hashmap in Java

Java offers various solutions that you can use to iterate over the map keys, values, or each key-value entry. Check the different approaches that you can use to iterate hashmap in Java

Using a For-Each Loop

The simplest approach to Java iterate map involves using a for-each loop to iterate over all the entries. The command for this approach is as follows:

// Java program to demonstrate iteration over 
// Map.entrySet() entries using for-each loop
import java.util.Map;
import java.util.HashMap;
class IterationDemo 
{
    public static void main(String[] arg)
    {
        Map<String,String> gfg = new HashMap<String,String>();
        // enter name/url pair
        gfg.put("GFG", "geeksforgeeks.org");
        gfg.put("Practice", "practice.geeksforgeeks.org");
        gfg.put("Code", "code.geeksforgeeks.org");
        gfg.put("Quiz", "www.geeksforgeeks.org");
        // using for-each loop for iteration over Map.entrySet()
        for (Map.Entry<String,String> entry : gfg.entrySet()) 
            System.out.println("Key = " + entry.getKey() +
                             ", Value = " + entry.getValue());
    }
}

Using an Iterator and a While Loop

This approach also uses the for-each syntax. But it involves using an iterator. The HashMap.entrySet() offers a set. Therefore, it helps in expanding the collection interface. As a result, you will be conveniently able to use the Iterator instance delivered by Map.entrySet().iterator. Check out the code below: 

public void iterateUsingForEachIterator(Map<String, String> map) {
    Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        String key = entry.getKey();
        String value = entry.getValue();
        System.out.println("Key=" + key + ", Value=" + value);
    }
}

Using For-Each and Lambda

This approach involves using lambda expressions, which have been a part of Java since version 8. A lambda expression will operate on input parameters to deliver a value. The lambda expression approach toward this issue does not require all key-value entries to be transformed into an entry set. Check out the code below:

public void iterateUsingLambda(Map<String, String> map) {
    map.forEach((key, value) -> {
        System.out.println("Key=" + key + ", Value=" + value);
    });
}

Also Read: Java Developer Salary in India

Conclusion

Among the three Java iterators, the enumeration interface is a deprecated one that has been replaced by the more functional iterator and list iterator interfaces. An iterator addresses the limitations of enumeration and is indispensable for any iteration programmer. The basics of Java iterator discussed in this article will help you get started with iterating collections in Java.

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

Q. Is Java a case-sensitive programming language?

Yes, Java is a case-sensitive language like Python and C++, meaning that it differentiates between the uppercase and the lowercase letters. The reason why it is case-sensitive is that it uses a C-style syntax. While using the code, the same letters or words could be deciphered differently based on their cases, as they create different variables, and even if the letters are same and in the same order, Java considers them differently.

Q. How can I remove an element from a Collection in Java?

A Collection in Java is a set of interfaces. There are two ways in which an element can be removed from Collections. One is by using Iterator, which is a type of iterator and another is by using Listiterator, which is another type of iterator in Java. The user can use the iterator method remove() to remove the current element in the Collection.

Q. Is Java easier to use than C++?

Java and C++ both are popular programming languages and have their own benefits and special features. However, Java is simpler, and the syntax used in it is much more readable than the one in C++, or any other programming language for that matter. Additionally, Java is more focused on Object-Oriented programming, and has a rich API. It lets the user experiment with different things like graphics, sounds, and others. Java is also a strongly typed language, which makes it easier for a beginner to identify their mistakes. So overall, it can be said that Java is easier than C++.

RELATED PROGRAMS