Iterator in Java: Understanding the Fundamentals of Java Iterator
By Rohan Vats
Updated on Jul 03, 2023 | 8 min read | 5.9k views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Jul 03, 2023 | 8 min read | 5.9k views
Share:
Table of Contents
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
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 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:
Check out upGrad’s Advanced Certification in Cyber Security
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:
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
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:
The different benefits of using an iterator in Java are as follows:
The different limitations of an iterator in Java are as follows:
The iterator interface can define the three key methods:
public boolean hasNext();
public Object next();
public void remove();
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:
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());
}
}
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);
}
}
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
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.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources