How to use iterator in java / Iterator tutorial in java

Iteration meaning
Iteration means traversing through the elements of a collection or an array one by one. This is generally required when you want to display the elements one by one or search for a particular element in the collection.


What is an iterator
An iterator is used to iterate(or loop) over the elements of a collection. Using an iterator, you can traverse through the elements of a collection one by one.
Though a collection can also be iterated by using a loop(such as for or while) but in case you want to remove elements from a collection during iteration, then iterator is the only choice(shown below).
An iterator in java is an object that implements java.util.Iterator interface. An iterator always iterates over a collection in forward order, you cannot reverse the order of iteration using an iterator.
Getting iterator
All collection classes provide an iterator using iterate method. That is, by calling iterate method on a list, set or queue, you can get an iterator over them.
iterate method is available to all collection classes that implement java.util.Collection interface. This is because iterate method is declared in java.util.Collection interface.
Map classes do not implement this interface, hence they do not have iterate method. Though they can be iterated indirectly using an iterator(shown later in this post).

Arrays cannot be iterated using an iterator.

List iterator example
As mentioned above, an iterator can be used to iterate over a list, set or a queue. Once you get an iterator over the collection to be iterated(or traversed), use its hasNext and next methods for iteration.
hasNext method determines whether there is an element remaining in the collection for iteration. It returns true if there is at least one element left to be iterated.
next method returns the current element of the collection where the iterator is positioned.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class ListIteratorExample {
 
   public static void main(String[] args) {
	// create a list
	List<String> list = new ArrayList<String>();
	// add elements
	list.add("orange");
	list.add("mango");
	list.add("papaya");
	// get iterator over the list
	Iterator<String> iterator = list.iterator();
	// iterate over the list
	while (iterator.hasNext()) {
		// get current element
		String element = iterator.next();
		System.out.println(element);
	}
   }
}

Output of above program is

mango
orange
guava


Note that iterator can be generic with its type the same as the type of collection on which it is iterating. List in the above example has a generic type of String, that it why the iterator also has the same generic type.
Set iterator example
Just like a list iterator, iteration over a set can also be performed as shown below.

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
 
public class SetIteratorExample {
 
   public static void main(String[] args) {
	// create a set
	Set<String> set = new HashSet<String>();
	// add elements
	set.add("orange");
	set.add("mango");
	set.add("papaya");
	// get iterator over the set
	Iterator iterator = set.iterator();
	// iterate over the set
	while (iterator.hasNext()) {
		// get current element
		String element = iterator.next();
		System.out.println(element);
	}
   }
}

Output of above program is

mango
orange
guava


Map iterator example
An iterator over a map cannot be obtained directly but over its set of keys or values which can then be used for iteration as shown in the below example.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class MapIteratorExample {
   public static void main(String[] args) {
	// create a hashmap
	Map<Integer, String> map = new HashMap<Integer, String>();
	// add values
	map.put(1, "mango");
	map.put(2, "orange");
	map.put(3, "guava");
	// get iterator over the keys of map
	Iterator<Integer> iterator = map.keySet().iterator();
	// iterate over map key
	while (iterator.hasNext()) {
		// get current map key
		Integer key = iterator.next();
		System.out.println("Key: " + key);
		// get value of this key
		System.out.println("Value: " + map.get(key));
	}
   }
}

Above code produces below output

Key: 1
Value: mango
Key: 2
Value: orange
Key: 3
Value: guava

A map can be iterated in many different ways. Check out all those here.

Removing elements using iterator
An iterator can be used to remove elements from a collection while iterating over it using remove method. This method will remove the element at which the iterator is currently positioned.
In other words, remove method of iterator will delete the element returned by its next method.

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
 
public class RandomNumberGenerator {
 
   public static void main(String[] args) {
	// create a set
	Set<String> set = new HashSet<String>();
	// add elements
	set.add("orange");
	set.add("mango");
	set.add("papaya");
	// get iterator over the set
	Iterator<String> iterator = set.iterator();
        // first element index
	int currentElementIndex = 0;
	System.out.println("Set before iteration: " + set);
        // iterate over the set
	while (iterator.hasNext()) {
		iterator.next();
                // remove second element 
		if(currentElementIndex == 1) {
			iterator.remove();
		}
                // increase element index
                ++currentElementIndex;
	}
	System.out.println("Set after iteration: " + set);
   }
}

Above code iterates over the set and removes its second element which is clear from the below output.

Set before iteration: [orange, papaya, mango]
Set after iteration: [orange, mango]

Note that this is the advantage of using an iterator that it can remove elements during iteration. If you are using a loop to iterate over a set or list and use the set’s remove method, then it will throw a java.util.ConcurrentModificationException.

More on ConcurrentModification exception here.

remove method will throw a java.lang.IllegalStateException if it is called before next is called. This makes sense because till the time next is not called, the iterator is not pointing to any element that it could remove.

In the above example, comment out or delete the statement iterator.next and this exception will be raised.

If you are creating your own custom collection class and want it to be iterated using an iterator, then make your class implement java.util.Iterable interface.

Hope this post helped you learn about iterator in java. Keep visiting!!!

0

Mark Your Impression

Close Menu