Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

Java Iterator Over Collection

1. Introduction to Java Iterator

The Java Iterator is a reference over a collection object. It can be ArrayList, LinkedList anything which implements the basic Collection Interface. With the iterator we can get all the items in the collection one by one. We can iterate over the collection via a loop or via a for-each construct. But, using these, we cannot adjust the structure while the iteration is in-progress. Whereas with Java Iterator, we can remove items while the iteration is going on.

Java Iterator is a Forward-Only Cursor. This means one can iterate the collection items only in forward direction. Standard Java Iterator does not allow the reverse way of iteration. Also, note the Standard Java Iterator does not allow adding the items even though it allows removal. In this example, we will learn about the Iterator using an ArrayList collection object.

2. Problem with For…Each – Remove Item

Now have a look at the below picture:

The for Each Loop
The for Each Loop

Here, we have a collection of strings, Fruits which represents fruit names. The foreach loop iterates over the fruits collection and prints the name of the fruit. This is a legal operation. But this also tries to remove all the fruit which holds the name Banana. The removal attempt fails as we try it on the iteration itself. Note, if we try to call the remove method outside of the loop, it will succeed.

The ‘for-each’ loop above will raise an Exception called ConcurrentModificationException. This exception will not be raised on the time when we call the remove method in loop. It will get raised when for each loop claims the next element in the Fruits collection. But how do we remove the elements while we are iterating it? The answer is via Iterator.

3. Java Iterator Methods

As already told in the preface, an Iterator is a special reference over the collection. In this section, we will find out how Java Iterator works. Let us say we have an ArrayList with six items in it, which you can see in the below picture:

ArrayList of Six Elements
ArrayList of Six Elements

We can get an iterator over this sex items by making a call to the iterator() method on the Collection object. In our case, the collection object is an ArrayList. The retrieved iterator will point to the very first element in the collection. In our case, the Java Iterator will be at the very first location, pointing at the element 100.

The hasNext() method returns true or false, which will be helpful to iterate over the collection. In our case, at this stage, if we make a call to the hasNext(), it will check “Is the Iterator is pointing to a Valid Element” and return true as Iterator is pointing the element 100. Some people will get confused with this method and think it will check for next element (101? No that is not right!).

The next() method will perform two actions. First it retrieves the item in the current location and moves the iterator forward. In our case, if we make a call to next, a) the iterator gets the item 100 b) advances the pointer to the next element which is 101. This shown below:

Java Iterator and its hasNext and next methods
Java Iterator and its hasNext and next methods

Now, we have enough information about the Java Iterator. Now, we will move ahead with the example.

4. Java Iterator Example

4.1 Prepare the ArrayList Collection

First, we create the ArrayList to store fruit collection. Then we store a set of fruits in that collection. The code is below:

Now in the ArrayList, we have a collection of fruits. Note, the fruits Apple, Orange & Banana are repeated in the collection. We will use this collection to explore Java Iterators.

4.2 ConcurrentModificationException

In the below code, we use the ForEach loop to iterate over fruits collection. When we try to delete a fruit (Line 6) the ‘for each’ loop throws exception. Note, the loop throws the ConcurrentModificationException exception on the for-loop construct while it tries to read next element and not at the remove method call itself.

4.3 Iterator’s next and hasNext

In the below code, at line 4, first we retrieve the iterator from our fruit collection by calling the function iterator(). Here, we form the loop using the hasNext function. The hasNext function returns false when there are no items to iterate. The function next() performs two actions. First, it gets the element at current location. Next, it moves the pointer to the next elements.

4.4 Remove Collection Item via Java Iterator

Next, we write the function iterateRemove which is taking two arguments. The first param is an ArrayList and the second one is the FruitName. The remove method call on the Iterator method removes an item in the collection. In our below example, we try to remove all the fruit that is passed as a second param.

This time, we will not get any exception and the deletion of the fruit succeeds. Note, here we deleted the fruits while we are iterating it. But, this was not allowed when we used a for..each loop.

5. Complete Code Example

Below is the complete code example:

6. Watch this Example in YouTube

Categories: Java

Tags: , , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.