Tuesday, August 10, 2021

How to use Iterator and ListIterator in Java? Example Tutorial

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-loopwhile-loopdo-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) There are two types of Iterators in Java, fail-fast, and fail-safe, check the difference between fail-safe and fail-fast Iterator for more details.

5) 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

16 comments :

Ravindra said...

I have heard about two types of Iterator in Java, fail-fast and fail-safe, Can you please explain difference between Fail-fast and Fail-Safe Iterators ?

Javin @ Spring interview questions said...

@Ravindra, fail-fast iterators are those who throw ConcurrentModificationException if collection is modified structurally by another thread when one thread is iterating over it. while fail-safe iterators are mostly work on copy of collection object instead of original collection object and hence not affected by such changes.

Rajiv said...

Hi Javin,
does iterator in Java and iterator design patterns are same thing or different ?

Solution & Technologies finder said...

Hi rajiv , design patterns is so difference than collection .design patterns follow the mvc pattern and iterator is a class which is retrieving/traverse data from array list and so..

Javin @ OutOfMemoryError in Java said...

@Rajiv, brother is correct. Iterator is a design pattern which allows to traverse or retrieve data and Java Iterator is just an implementation of that pattern. Thanks Rajiv and brother for your comments.

Anonymous said...

Simple and best Java Iterator Tutorial. Iterator in Java looks confusing to me initially but after reading your tutorial now I can use Java iterator and now thinking to write my own iterator by implementing iterator interface, would be great if you could share guide lines on writing your iterator in Java

Anonymous said...

I want to implement my own Iterator in Java, Can you please let us know how to write own iterator in Java with sample code, thanks.

Sonya said...

What is benefit of using iterator in Java, Can't we do iteration using for loop? with java5 for loop its even more clean and easy rather than using an Iterator object which I am sure take more memory.

Anonymous said...

What is benefit of using Iterator over for each loop or simply for loop with index? Did you measure performance of Iterator for different collections like ArrayList, LinkedList or HashSet?

Unknown said...

very nice explanation of iterator concept.I was confused about iterator concept,but now clear after reading this block.

Anonymous said...

Can you give me an example of Fail Fast Iterator and FailSafe Iterator

Unknown said...

can you please tell me what is the design pattern used in iterator

Unknown said...

How to retrieve values in a table using list????Please answer.
I created database table in one class and list in another class.

suyash said...

2nd point is not working i.e "If you want to remove objects from Collection than don't use for-each loop instead use Iterator's remove() method to avoid any ConcurrentModificationException".

If List itself is not concurrent i.e If it is not CopyOnWriteArrayList then iterator throws concurrent exception while calling remove method.

List str = new ArrayList();

str.add("abc");
str.add("aa");
str.add("abcs");

Iterator itr = str.iterator();

while(itr.hasNext()){
str.remove("abc"); // throws Exception in thread "main" java.util.ConcurrentModificationException.
}



javin paul said...

Dear @suresh, you are not calling Iterator's remove method, instead you are calling ArrayList's remove method which is the cause of ConcurrentModificationException.

You are doing str.remove("abc");

Instead, you should do :
itr.remove("abc");

Don't worry this is the classic mistake every Java developer make, Even I have made it before and spent countless hour to find where is that other thread which is modifying this collection :) , didn't know that time that you can get this exception even with single threaded code.

Anonymous said...

Iterator returned by synchronized Collection are fail-fast while iterator returned by concurrent collections are fail-safe in Java.

worth adding

Post a Comment