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
Explore Our Software Development Free Courses
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); Â Â Â }); }
Explore our Popular Software Engineering Courses
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.
In-Demand Software Development Skills
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.
Read our Popular Articles related to Software Development
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++.