Iterator
java.util.Iterator
INTERFACE
tip
REFERENCE:~
- Official Documentation:-
Java 14
java.util.Iterator
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Iterator.html - https://www.javatpoint.com/java-iterator#:~:text=In%20Java%2C%20an%20Iterator%20is,components%20entirety%20one%20by%20one.&text=The%20Java%20Iterator%20is%20also,classes%20of%20the%20Collection%20framework.
caution
Advantage:~
- The user can apply these iterators to any of the classes of the Collection framework.
- In Java Iterator, we can use both of the read and remove operations.
- If a user is working with a for loop, they cannot modernize(add/remove) the Collection, whereas, if they use the Java Iterator, they can simply update the Collection.
- The Java Iterator is considered the Universal Cursor for the Collection API.
Disadvantage:~
- The Java Iterator only preserves the iteration in the forward direction. In simple words, the Java Iterator is a uni-directional Iterator.
- The replacement and extension of a new component are not approved by the Java Iterator.
- In CRUD Operations, the Java Iterator does not hold the various operations like CREATE and UPDATE.
- In comparison with the Spliterator, Java Iterator does not support traversing elements in the parallel pattern which implies that Java Iterator supports only Sequential iteration.
- In comparison with the Spliterator, Java Iterator does not support more reliable execution to traverse the bulk volume of data.
Declaration
HashSet<String> collectionVaribleName = new HashSet<>();
Iterator<wrapperClassDataType> iteratorVariableName = collectionVaribleName.iterator();
// 👆 Here ".iterator()" method is a method of the "Collection" used:~ "HashSet" is used above
Iterator methods
hasNext()
info
hasNext()
method ofIterator
Interface returns true if there are more elements left in the iteration. If there are no more elements left, then it will return false.hasNext()
method ofIterator
Interface does not accept any parameter.- It is used as
while (it.hasNext())
similar towhile (sc.hasNext())
HashSet<String> hs = new HashSet<>();
while (sc.hasNext()) {
hs.add(sc.next());
}
Iterator<Integer> it = hs.iterator(); // Here ".iterator()" method is a method of `HashSet" class :~ "java.util.HashSet.iterator()"
while (it.hasNext()) { // ".hasNext()" method is a method of `Iterator" Interface
System.out.print(it.next() + " "); // ".next()" method is a method of `Iterator" Interface
}
next()
info
next()
returns E, i.e., the next element in the traversal. If the iteration or collection of objects has no more elements left to iterate, then it throws the NoSuchElementException.It also does not accept any parameter.it.next()
is similar tosc.next()
while (it.hasNext()) { // ".hasNext()" method is a method of `Iterator" Interface
System.out.print(it.next() + " "); // ".next()" method is a method of `Iterator" Interface
}