How to use Iterator and ListIterator in Java? Example Tutorial (original) (raw)

Iterator in Java is nothing but a traversing object, made specifically for Collection objects like List and Set. we have already aware about different kind of traversing methods like for-loop, while-loop, do-while, for each lop, etc, they all are index-based traversing but as we know Java is purely object-oriented language there is always possible ways of doing things using objects so Iterator is a way to traverse as well as access the data from the collection. Even with traversing with objects, we have Enumeration, Iterator, and ListIterator in Java which we will in this Java Iterator tutorial.

What is Iterator in Java API:

Java iterator is an interface that belongs to the collection framework that allows us to traverse the collection and access the data element of collection without bothering the user about the specific implementation of that collection. Basically, the List and set collection provide the iterator.

You can get Iterator from ArrayList, LinkedList, and TreeSet, etc. Map implementation such as HashMap doesn’t provide an Iterator directory but you can get their keySet or Value Set and can iterator through that collection.

Syntax:

It comes inside java.util package. as public interface Iterator and contains three methods:

boolean hasNext(): this method returns true if this Iterator has more elements to iterate.

Object next(): return the next element in the collection until the hasNext() method return true. Its always recommended to call hasNext() method before calling next() method to avoid java.util.NoSuchElementException: Hashtable Iterator

remove(): method removes the last element return by the iterator this method only calls once per call to next().

How to create Iterator in Java:

Iterator in Java, Java Iterator Example Program,ListIterator tutorialEvery collection classes provides an iterator() method that returns an iterator to the beginning of the collection. By using this iterator object, we can access each element in the collection, one element at a time. In general, to use an iterator to traverse through the contents of a collection follow these steps:

  1. First obtain an iterator to the beginning of the collection by calling the collection's iterator( )
  2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
  3. Within the loop, obtain each element by calling next( ).

Java Iterator tutorial and Example

Example of How to use Iterator in Java

Here is complete code example of How to use Iterator in Java. This Java program creates Hashtable, populate it with dummy data and than uses Iterator to traverse Map and prints key and value for each Entry. This Java Program uses Generic version of Iterator to ensure type-safety and 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 use Iterator in Java to loop through all elements * of Collection classes like ArrayList, LinkedList, HashSet or Map implementation like * HashMap,TreeMap and Hashtable. */
public class IteratorExample{

public static void main(String[] args) {
//Hashtable instance used for Iterator Example in Java
Hashtable<**Integer**, **String**> stockTable=new Hashtable<**Integer**,**String**>();

//Populating Hashtable instance with 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 in Java, here Map implementation is Hashtable
Iterator<Entry<**Integer**, **String**>> i= stockSet.iterator();
System.out.println("Iterating over Hashtable in Java");

//Iterator begins
while(i.hasNext()){
Map.Entry<**Integer**,**String**> m=i.next();
int key = m.getKey();
String value=m.getValue();
System.out.println("Key :"+key+" value :"+value);

}
System.out.println("Iteration over Hashtable finished");
}
}

Output:
Iterating over Hashtable in Java
Key :4 value :Four
Key :3 value :Three
Key :2 value :One
Key :1 value :Two
Iteration over Hashtable finished

Why use Iterator when we have Enumerator:

Both Iterator and Enumerator are used for traversing of the collection but Iterator is more enhanced in terms of extra method remove () it provide us for modifying the collection which is not available in enumeration along with that it is more secure it doesn’t allow another thread to modify the collection when some another thread is iterating the collection and throws concurrentModificationException. Along with this method name are also very convenient in Iterator which is not a major difference but makes use of iterator easier.

What is List Iterator in Java?

ListIterator in Java is an Iterator that allows users to traverse Collections like ArrayList and HashSet in both directions by using methods previous() and next (). You can obtain ListIterator from all List implementations including ArrayList and LinkedList. ListIterator doesn’t keep the current index and its current position is determined by a call to next() or previous() based on the direction of traversing.

Important points about Iterator in Java:

  1. Iterator in Java support generics so always use the Generic version of Iterator rather than using Iterator with raw type.

  2. If you want to remove objects from Collection then don't use a for-each loop instead use Iterator's remove() method to avoid any ConcurrentModificationException.

  3. Iterating over a collection using Iterator is subject to ConcurrentModificationException if Collection is modified after Iteration started, but this only happens in case of fail-fast Iterators.

  4. List collection type also supports ListIterator which has to add() method to add elements in the collection while Iterating. There are some more differences between Iterator and ListIterator like bidirectional traversing, which we have discussed above. Also why ListIterator has add () method is a popular Java Collection Interview question.

Some of my other Java Program tutorials you may find interesting