Iterator inwards Java is zippo but a traversing object, made specifically for Collection objects similar List and Set. nosotros bring already aware near dissimilar sort of traversing methods similar for-loop ,while loop,do-while,for each lop etc,they all are index based traversing but equally nosotros know Java is purely object oriented language at that topographic point is ever possible ways of doing things using objects then Iterator is a agency to traverse equally good equally access the information from the collection. Even alongside traversing alongside object nosotros bring Enumeration, Iterator together with ListIterator inwards Java which nosotros volition inwards this Java Iterator tutorial.
What is Iterator inwards Java API:
Java iterator is an interface belongs to collection framework allow us to traverse the collection together with access the information chemical ingredient of collection without bothering the user near specific implementation of that collection it. Basically List together with laid collection provides the iterator. You tin larn Iterator from ArrayList, LinkedList, together with TreeSet etc. Map implementation such equally HashMap doesn’t render Iterator directory but y'all tin larn at that topographic point keySet or Value Set together with tin iterator through that collection. Syntax:
It comes within java.util package. equally public interface Iterator and contains 3 methods:
boolean hasNext(): this method returns truthful if this Iterator has to a greater extent than chemical ingredient to iterate.
Object next(): return the side past times side chemical ingredient inwards the collection until the hasNext() method render true. Its ever recommended to telephone yell upwardly hasNext() method earlier calling next() method to avoid java.util.NoSuchElementException: Hashtable Iterator
remove(): method take the terminal chemical ingredient render past times the iterator this method alone calls 1 time per telephone yell upwardly to next().
How to create Iterator inwards Java:
Every collection classes provides an iterator() method that returns an iterator to the get-go of the collection. By using this iterator object, nosotros tin access each chemical ingredient inwards the collection, 1 chemical ingredient at a time. In general, to purpose an iterator to traverse through the contents of a collection follow these steps:
1. First obtain an iterator to the beginning of the collection past times calling the collection's iterator( )
2. Set upwardly a loop that makes a telephone yell upwardly to hasNext( ). Have the loop iterate equally long equally hasNext( ) returns true.
3. Within the loop, obtain each chemical ingredient past times calling next( ).
1. First obtain an iterator to the beginning of the collection past times calling the collection's iterator( )
2. Set upwardly a loop that makes a telephone yell upwardly to hasNext( ). Have the loop iterate equally long equally hasNext( ) returns true.
3. Within the loop, obtain each chemical ingredient past times calling next( ).
Java Iterator tutorial together with Example
Example of How to purpose Iterator inwards Java
Here is consummate code representative of How to purpose Iterator inwards Java. This Java programme creates Hashtable, populate it alongside dummy information together with than uses Iterator to traverse Map together with prints fundamental together with value for each Entry. This Java Program uses Generic version of Iterator to ensure type-safety together with avoid casting .
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Simple Java Program which shows How to purpose Iterator inwards Java to loop through all elements
* of Collection classes similar ArrayList, LinkedList, HashSet or Map implementation like
* HashMap,TreeMap together with Hashtable.
*/
public class IteratorExample{
public static void main(String[] args) {
//Hashtable instance used for Iterator Example inwards Java
Hashtable<Integer, String> stockTable=new Hashtable<Integer,String>();
//Populating Hashtable instance alongside sample values
stockTable.put(new Integer(1), "Two");
stockTable.put(new Integer(2), "One");
stockTable.put(new Integer(4), "Four");
stockTable.put(new Integer(3), "Three");
//Getting Set of keys for Iteration
Set<Entry<Integer, String>> stockSet = stockTable.entrySet();
// Using Iterator to loop Map inwards Java, hither Map implementation is Hashtable
Iterator<Entry<Integer, String>> i= stockSet.iterator();
System.out.println("Iterating over Hashtable inwards Java");
//Iterator begins
while(i.hasNext()){
Map.Entry<Integer,String> m=i.next();
int fundamental = m.getKey();
String value=m.getValue();
System.out.println("Key :"+key+" value :"+value);
}
System.out.println("Iteration over Hashtable finished");
}
}
Output:
Iterating over Hashtable inwards Java
Key :4 value :Four
Key :3 value :Three
Key :2 value :One
Key :1 value :Two
Iteration over Hashtable finished
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Simple Java Program which shows How to purpose Iterator inwards Java to loop through all elements
* of Collection classes similar ArrayList, LinkedList, HashSet or Map implementation like
* HashMap,TreeMap together with Hashtable.
*/
public class IteratorExample{
public static void main(String[] args) {
//Hashtable instance used for Iterator Example inwards Java
Hashtable<Integer, String> stockTable=new Hashtable<Integer,String>();
//Populating Hashtable instance alongside sample values
stockTable.put(new Integer(1), "Two");
stockTable.put(new Integer(2), "One");
stockTable.put(new Integer(4), "Four");
stockTable.put(new Integer(3), "Three");
//Getting Set of keys for Iteration
Set<Entry<Integer, String>> stockSet = stockTable.entrySet();
// Using Iterator to loop Map inwards Java, hither Map implementation is Hashtable
Iterator<Entry<Integer, String>> i= stockSet.iterator();
System.out.println("Iterating over Hashtable inwards Java");
//Iterator begins
while(i.hasNext()){
Map.Entry<Integer,String> m=i.next();
int fundamental = m.getKey();
String value=m.getValue();
System.out.println("Key :"+key+" value :"+value);
}
System.out.println("Iteration over Hashtable finished");
}
}
Output:
Iterating over Hashtable inwards Java
Key :4 value :Four
Key :3 value :Three
Key :2 value :One
Key :1 value :Two
Iteration over Hashtable finished
Why purpose Iterator when nosotros bring Enumerator:
Both Iterator and Enumerator is used for traversing of collection but Iterator is to a greater extent than enhanced inwards price of extra method remove () it render us for alteration the collection which is non available inwards enumeration along alongside that it is to a greater extent than secure it doesn’t allow about other thread to alteration the collection when about some other thread is iterating the collection together with throws concurrentModificationException. Along alongside this method mention are likewise really convenient inwards Iterator which is non major departure but brand purpose of iterator to a greater extent than easy.
What is List Iterator inwards Java?
ListIterator in Java is an Iterator which allows user to traverse Collection similar HashSet in both management past times using method previous() and next (). You tin obtain ListIterator from all List implementation including ArrayList together with LinkedList. ListIterator doesn’t survive along electrical flow index together with its electrical flow seat is determined past times telephone yell upwardly to next() or previous() based on management of traversing.
Important signal near Iterator inwards Java:
1) Iterator inwards Java back upwardly generics then ever purpose Generic version of Iterator rather than using Iterator alongside raw type.
2) If y'all desire to take objects from Collection than don't purpose for-each loop instead purpose Iterator's remove() method to avoid whatever ConcurrentModificationException.
3) Iterating over collection using Iterator is bailiwick to ConcurrentModificationException if Collection is modified later Iteration started, but this alone happens inwards representative of fail-fast Iterators.
4) There are 2 types of Iterators inwards Java, fail-fast together with fail-safe, banking concern lucifer difference betwixt fail-safe together with fail-fast Iterator for to a greater extent than details.
5) List collection type likewise supports ListIterator which has add() method to add together elements inwards collection spell Iterating. There are about to a greater extent than differences betwixt Iterator together with ListIterator similar bidirectional traversing, which nosotros bring discussed above. Also why ListIterator has add() method is a popular Java Collection Interview question.
Further Learning
Java In-Depth: Become a Complete Java Engineer
Advanced usage of Enum inwards Java alongside Example