If you are working on a number program and say you want to print a sequence, that’s where Iterator in Java comes into the picture. This way you can get the sequence even without adding the print statement for each and every line. So, let’s learn about Iterator in Java.
Below are the topics that I’ll be covering in this module:
Let’s get started!
What is an iterator?
Java mainly supports four different cursors. They are namely:
- Enumeration
- Iterator
- ListIterator
- Spliterator
Each of these Java cursors have some advantages and drawbacks. We’ll focus on Iterator in this article.
Now, what is an iterator in Java?
Iterator is an interface that belongs to a collection framework. It allows you to traverse the collection, accesses the data element and removes the data elements of the collection.
It is also considered as a Universal iterator as you can apply it to any Collection object. By using an Iterator, you can perform both read and remove operations. This is an improved version of Enumeration with the additional functionalities of remove-ability of an element.
Java Iterator Methods
Java iterator has 4 methods in total. Let’s understand them in detail.
Methods | Description |
---|---|
forEachRemaining(Consumer<? super E>action) | It performs the actions on each of the element until and unless all the elements have been processed. Also until an exception is thrown by the action. |
hasNext() | This returns a true value if a high number of elements are encountered during iteration. |
next() | This returns the next specified element during the iteration. |
remove() | This method removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ). |
boolean hasNext() | This returns true if the iteration has more elements. |
Example:
class Method{ public static void main(String[] args) ArrayList<String> list = new ArrayList<String>(); list.add("E"); list.add("D"); list.add("U"); list.add("R"); list.add("E"); list.add("K"); list.add("A"); // Iterator to traverse the list Iterator iterator = list.iterator(); System.out.println("List elements : "); while (iterator.hasNext()) System.out.print(iterator.next() + " "); System.out.println(); } }
Output: EDUREKA
Let’s take a look at ListIterator in Java.
ListIterator in Java
ListIterator in Java is an Iterator that allows users to traverse through the Collection in both directions. It contains the following methods:
Methods | Method & Description |
---|---|
void add(Object obj) | Inserts obj into the list in front of the element that will be returned by the next call to next( ). |
boolean hasNext( ) | Returns true if there is the next element. Otherwise, returns false. |
boolean hasPrevious( ) | Returns true if there is a previous element. Otherwise, returns false. |
Object next( ) | Returns the next element. A NoSuchElementException is thrown if there is not the next element. |
int nextIndex( ) | Returns the index of the next element. If there is not the next element, returns the size of the list. |
Object previous( ) | Returns the previous element. A NoSuchElementException is thrown if there is not a previous element. |
int previousIndex( ) | Returns the index of the previous element. If there is not a previous element, returns -1. |
void remove( ) | Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked. |
void set(Object obj) | Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ). |
Example:
public class Lists { public static void main(String args[]) { // Create an array list ArrayList al = new ArrayList(); // add elements to the array list al.add("E"); al.add("D"); al.add("U"); al.add("R"); al.add("E"); al.add("K"); al.add("A"); // Use iterator to display contents of al System.out.print("Original contents of al: "); Iterator itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } System.out.println(); // Modify objects being iterated ListIterator litr = al.listIterator(); while(litr.hasNext()) { Object element = litr.next(); litr.set(element + "+"); } System.out.print("Modified contents of al: "); itr = al.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } System.out.println(); // Now, display the list backwards System.out.print("Modified list backwards: "); while(litr.hasPrevious()) { Object element = litr.previous(); System.out.print(element + " "); } System.out.println(); } }
Output:
Original contents of al: E D U R E K A
Modified contents of al: E+ D+ U+ R+ E+ K+ A+
Modified list backwards: A+ K+ E+ R+ U+ D+ E+
Now, let’s take a look at the advantages and limitations of this iterator interface in Java.
Advantages of Iterator in Java
Iterator in Java has the following advantages.
- You can use these iterators for any Collection class.
- Iterator in Java supports both read as well as remove operations.
- If you are using for loop you cannot update(add/remove) the Collection whereas with the help of an iterator you can easily update Collection.
- It is a Universal Cursor for the Collection API.
- The method names are very simple and are very easy to use.
Limitations of Iterator in Java
Iterators in Java has the following drawbacks:
- You can only perform forward direction iteration, that is Uni-Directional Iterator.
- Replacement and addition of a new element is not supported by the Iterator.
- ListIterator is the most powerful iterator but it is only applicable for List implemented classes. So it is not a Universal iterator.
- When you use CRUD Operations, it does not support the create and update operations.
- When you compare it with Spliterator, it does not let you iterate elements parallel. This means it supports only Sequential iteration.
- It does not support better performance to iterate a large volume of data.
This brings us to the end of this article where we have learned about how iterator in Java work. Hope you are clear with all that has been shared with you in this tutorial.
If you found this article on “Iterator in Java” relevant, check out the Edureka Java Certification Training, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.
We are here to help you with every step on your journey, besides this, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
If you come across any questions, feel free to ask all your questions in the comments section of “Iterator in Java” and our team will be glad to answer.