Java Iterator
When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of cursors. They are namely
- Iterator
- Enumeration
- ListIterator
In this article we are only discussing about the Iterator. The syntax, examples and methods are also discussed in this article.
Iterator
The Collection framework in Java uses iterators to get objects each one individually. Given that we may use it on any Collection object, it is a generic iterator. We can execute retrieve and eliminate functions using Iterator. With the added ability to remove an object, it is an enhanced form of Enumeration.
All Collection framework-implemented protocols, such as Set, List, Queue, Deque, and all supported classes of Data structure, need the use of an iterator anytime we want to iterate elements. For the complete collection framework, only the iterator cursor is exposed.
Syntax
Iterator itr = c.iterator();
Iterator Methods
Each Collection class provides the iterator() function. When using an iterator to cycle over a collection's data, first get an iterator to the collection's beginning by invoking the iterator() function on the collection. Establish a sequence that calls hasNext after that ( ). Keep repeating the loop until hasNext() yields true. Lastly, inside that loop, call next to get each element ( ).
The iterator interface consists of 3 methods:
- hasNext()
- next()
- remove()
- forEachRemaining()
hasNext()
There are no parameters accepted by the procedure. If there are still more components in the iteration, it satisfies the condition. It will result false if there are no further values.It is not necessary to invoke the next() method if there are no further components in the iteration. In simple terms, we can explain that the method is employed in order decide whether or not to invoke the next() method.
next()
It is comparable to the method hasNext(). Additionally, it doesn't take any parameters. It gives back E, the following element with in propagation. The NoSuchElementException is thrown if the iterative process or object collection runs out of factors to iterate.
remove()
There are no parameters needed for this technique either. This method doesn't have a return type. This method's primary purpose is to eliminate the final member that the iterator returned after going through the original collection. Only a small number of times per subsequent () method call how could the remove () method be requested. The iterator throws the UnSupportedOperationException if it is unable to support the remove method. If the following method has not yet been invoked, it also causes the IllegalStateException.
forEachRemaining()
It is the one Java Iterator method that accepts an input. Action is accepted as a variable. Action is simply what needs to be done. This method has no return type. until each of the left collection elements have been used or the function raises an exception, this method applies the specific individual operation to each of the left collection elements. Action throws exceptions, which are communicated to the caller. It throws a NullPointerException if the method is null.
Example
Let’s go through the simple program to understand the iterator. The program goes in the following manner.
Demo1.java
import java.io.*;
import java.util.*;
public class Demo1 {
public static void main(String[] args)
{
ArrayList<String> carModels = new ArrayList<String>();
carModels.add("Audi");
carModels.add("Mustang");
carModels.add("Ford");
carModels.add("Ferrari");
carModels.add("Land Rover");
Iterator it = carModels.iterator();
System.out.println("Car Models : ");
while (it.hasNext())
System.out.println(it.next() + " ");
System.out.println();
}
}
Output
Car Models :
Audi
Mustang
Ford
Ferrari
Land Rover
Advantages
- These iterators can be used with any of the Collection package's classes, according to the users.
- The read as well as remove functions are both fully functional in Java Iterator.
- When using a for loop, an user can't modify (add or remove items from) the Collection; but, if they use a Java Iterator, they can easily do so.
- For the Collection API, the Java Iterator is regarded as the Global Pointer.
- The Java Iterator has very straightforward method names that are also very convenient when using.
Disadvantages
- The Java Iterator just keeps track of iterations that move ahead. A Java Iterator is just a single - mode Iterator, to put it simply.
- The Java Iterator does not support the replacement or expansion of a new component.
- The Java Iterator sometimes doesn't store the multiple functions like CREATE and UPDATE in CRUD Operations.
- Java Iterator only provides Consecutive iteration since, in contrast to the Spliterator, it does not provide traversal components in the continuous path.
- Java Iterator does not enable more dependable performance to examine the large amount of information in contrast to Spliterator.