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:

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:

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:

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:
1 2 3 4 5 6 7 8 9 10 11 12 |
//Sample 02: Create an Array List ArrayList<String> Fruits = new ArrayList<String>(); Fruits.add("Apple"); Fruits.add("Orange"); Fruits.add("Banana"); Fruits.add("Orange"); Fruits.add("Apple"); Fruits.add("Banana"); Fruits.add("Apple"); Fruits.add("Orange"); Fruits.add("Orange"); Fruits.add("Banana"); |
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.
1 2 3 4 5 6 7 8 |
for(String fruit: Fruits) { System.out.print(fruit + " "); if (fruit.equalsIgnoreCase("Banana")) { Fruits.remove(fruit); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private static void iterateList(ArrayList<String> Fruits) { System.out.println("The Fruit Lists:"); //4.1 Get the Iterator Iterator<String> itr = Fruits.iterator(); //4.2 Iterate Over the ArrayList while(itr.hasNext()) { String str = itr.next(); System.out.println(str); } System.out.println("================"); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
//Sample 04: Iterate Over as List private static void iterateRemove(ArrayList<String> Fruits, String FruitName) { //4.1 Iterate Over the List Iterator<String> itr = Fruits.iterator(); while(itr.hasNext()) { String str = itr.next(); //4.2 Remove an Element if (str.equals(FruitName)) itr.remove(); } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
//Sample 01: Iterators import java.util.ArrayList; import java.util.Iterator; public class MainEntry { public static void main(String[] args) { //Sample 02: Create an Array List ArrayList<String> Fruits = new ArrayList<String>(); Fruits.add("Apple"); Fruits.add("Orange"); Fruits.add("Banana"); Fruits.add("Orange"); Fruits.add("Apple"); Fruits.add("Banana"); Fruits.add("Apple"); Fruits.add("Orange"); Fruits.add("Orange"); Fruits.add("Banana"); //Sample 02a: Iterate using Foreach for(String fruit: Fruits) { System.out.print(fruit + " "); if (fruit.equalsIgnoreCase("Banana")) { Fruits.remove(fruit); } } //Sample 03: Iterator Start from Head, Moves Forward iterateList(Fruits); //Sample 04: Now we will Remove iterateRemove(Fruits, "Apple"); iterateList(Fruits); } //Sample 03: Iterate Over as List private static void iterateList(ArrayList<String> Fruits) { System.out.println("The Fruit Lists:"); //3.1 Get the Iterator Iterator<String> itr = Fruits.iterator(); //3.2 Iterate Over the ArrayList while(itr.hasNext()) { String str = itr.next(); System.out.println(str); } System.out.println("================"); } //Sample 04: Iterate Over as List private static void iterateRemove(ArrayList<String> Fruits, String FruitName) { //4.1 Iterate Over the List Iterator<String> itr = Fruits.iterator(); while(itr.hasNext()) { String str = itr.next(); //4.2 Remove an Element if (str.equals(FruitName)) itr.remove(); } } } |
6. Watch this Example in YouTube
Categories: Java
Tags: ConcurrentModificationException, hasNext, iterator, next, remove