Monday, April 10, 2023

How to use Iterator Java - Example Tutorial

The Iterator is used to iterate over all elements of a Collections in Java. By Iteration, I mean, going over each element stored in the collection and optionally performing some operation like printing value of an element, updating object or removing an object from Collection. Iterator was not part of the first Java release, and a similar class Enumeration was there to provide Iteration functionality. Iterator in Java was introduced from JDK 1.4 and it provides an alternative to Enumeration, which is obsolete nowadays. An iterator is different from Enumeration in two main ways, first, Iterator allows a programmer to remove elements from Collection during iteration.

Second, names are shortened and improved in Iterator, by the way, you can see the difference between Iterator and Enumeration for more differences.

It's one of the frequently asked Java Interview questions. An iterator is an interface and enhanced to support Generic from Java 1.5 release.

Almost all popular collection implements Iterator, including ArrayList, LinkedList, and HashSet. hasNext() method of Iterator is used as a condition while Iterating, and next() method actually returns an object, next in sequence maintained by Collection itself.

In this Java programming tutorial, we will learn How to use Iterator in Java by coding Iterator example and iterating over ArrayList.




How to use Iterator in Java - Example

Java program to use Iterator in Java with collectionUsing Iterator is probably the simplest thing you will learn in Java programming. Every Collection, which implements the Iterator interface, provides iterator() method which returns the Iterator instance. This method comes from java.util.Iterator interface and return a type-safe Iterator.

Now, In order to start iterating or navigating, we can use the while loop and hasNext() method to check whether there are more elements in Iterator or not. In each run of the while loop, we get access to one element from Java Collection.

In this example, we first print the value of the element and subsequently remove it from Collection. So, at the end of our iteration, the Java collection should be empty.

By the way, It's also worth knowing that there are two kinds of Iterator in Java, fail-safe and fail-fast. fail-safe Iterator doesn't throw ConcurrentModificationException during iteration while fail-fast does, if, Iterator realizes any structural change in Collection once Iteration begins.



Java Iterator Example

Without, delaying anymore, here is our Java program to show, How to use Iterator in Java.

/**
 * Java program to show, How to use Iterator in Java.
 * Iterator provides a convenient way to access every element from Java Collections.
 * Iterator is also handy in removing elements from Collection.
 * @author java67
 */
public class IteratorHowTo {

    public static void main(String args[]) {
     
 
        //This is nice way to create List, but it's fixed lenght, 
        //don't supprot remove()
        List<String> androidVersions = Arrays.asList("Petit Four", "Cupcake", "Donut",
                                              "Eclair", "Froyo","Gingerbread",
                                              "Honeycomb", "Ice Cream Sandwich",
                                              "Jelly Bean");
       
        //this is bettern than adding individual elements - No?
        List<String> android = new ArrayList<String>(androidVersions);
       
       
        //Getting Iterator from List
        Iterator<String> iterator = android.iterator();
       
        System.out.println("Size of List before Iteratation " + android.size());
       
        //Using Iterator to iterate over List, acces object one by one
        while(iterator.hasNext()){
            String version = iterator.next();
            System.out.println(version);
            /* android.remove(version); */ //removing object from List - 
                       ConcurrentModificationException
            
            iterator.remove();  // you should be using Iterator's remove method
        }
       
        System.out.println("Size of list after removing object during Iteration : "
                               + android.size());
    }
}

Output:
Size of List before Iteratation 9
Petit Four
Cupcake
Donut
Eclair
Froyo
Gingerbread
Honeycomb
Ice Cream Sandwich
Jelly Bean
Size of list after removing object during Iteration : 0


There are a couple of interesting things to note in this code. First thing is a nice way of creating List in one line, This is the best way to create a List if you know values in advance.

Unfortunately, that List is a fixed length List and doesn't support remote operation, calling remove() will result in "Exception in thread "main" java.lang.UnsupportedOperationException".

By the way, it's important to remember that this is not a read-only Collection, you can still modify existing elements by using the set(index) method.

How to use Iterator in Java


The second interesting thing is using the copy constructor of Collection, which is a nice way to copy elements from one Collection to another. See Java Fundamentals: Collections to learn more about copying elements from one Collection to another. It's a free, online Java course by Richard Warburton and Pluralsight.

Now last and probably most important thing to note is using the iterator.remove() method to remove objects from List.

Many programmer make mistake by calling List.remove() method instead of Iterator.remove() here, earlier will throw ConcurrentModificationException.

You should only use the remove() method from java.util.Iterator to remove elements from the collection, while iterating.

That's all about How to use Iterator in Java. Though we have seen a relatively simple example of Java Iterator, it does demonstrate the most common usage of Iterator.

Btw, just beware of ConcurrentModificationExcepton, while iterating over Java Collections in a multi-threading environment.

Though, most of the Concurrent Collections such as ConcurrentHashMap and CopyOnWriteArrayList supports fail-safe Iterator, more popular ones like ArrayList or HashSet iterators are still fail-fast.



Further Learning
5 differences between HashMap vs Hashtable in Java
Difference between ConcurrentHashMap and HashMap in Java
Difference between Vector vs ArrayList in Java

Thanks for reading this tutorial, if you like this tutorial then please share it with your friends and colleagues.

4 comments:

  1. Thank you so much for your post. So interesting details about iterators.

    ReplyDelete
  2. I am still unsure, Why Iterator is such an important class. I like to use loops for all iteration or traversal need, they seems to me provide more control, and readable code. Does anyone knows, real purpose of Iterator class in Java?

    ReplyDelete
  3. Simply nice tutorial. I need to use iterator while programming with SocketChannel selectionkeys

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.