Iterator in Java

Iterator in Java

Whenever we talk about traversing the Collection first more thing comes in mind apart from for loop is to use an iterator. But the question comes what is an iterator and how it’s works. We will be discussing about Iterator in-depth in this post. Then what we are waiting for let’s get rolling.

What is Iterator in Java?

Iterator helps to iterate or traverse over Java Collection. This is a cursor-based system used to traverse the element in Collection like List, Stack, Queue and etc. When we say Its cursor-based system then it means that Iterator uses the cursor to visit each of its elements and performs an operation on the visited element.

Iterator interface provide several methods that need to get implemented by the implementing class.

Iterator Methods in Java

Iterator provides several methods that will help ways to traverse the collection.

default void forEachRemaining(Consumer<? super E> action)This method performs given action to all remaining elements of the collection until all elements are processed or Throws Exception
boolean hasNext()this method will return true if the iterator has more elements to traverse.
E next()next() the method moves the cursor to the next element and returns that element.
default void remove()remove() the method will remove an element at that curser from the collection on which iterator is called.

Basic Iterator Example

	private static void iterateList() {
		List<String> list = new ArrayList<String>();
		list.add("India");
		list.add("US");
		list.add("China");
		list.add("America");
		System.out.println("Intial Content of the list is: "+ list);

		Iterator<String> iterator = list.iterator();
		int count = 0;
		while(iterator.hasNext()) {
			if(count == 1) {
                //Move the pointer from india to china
				iterator.next();
                //Remove China from the list.
				iterator.remove();
			}
			System.out.println(iterator.next());
			count++;
		}
		System.out.println("Content of the list is: "+ list);
		
	}

Output of above code

Intial Content of the list is: [India, US, China, America]
India
China
America
Content of the list is: [India, China, America]

In the above code we saw that we created a list with

[India, US, China, America]

and with help of iterator that we retrieved from calling iterator() on created list. When we created our iterator, then we have something like this

Iterator for list
Iterator for list

Initially cursor is at 0 in above image.

When we do iterator.hasNext() then it check’s, does we have element at next position i.e at position 1

And if it found the element is there at next index then we perform iterator.next() which will do two task first it will move the cursor to next point i.e 1

cursor moved to 1
cursor moved to 1

and also returns the element at index 1 i.e India. That’s why to iterate over entire list we are using while loop to check availability of the next element as while(iterator.hasNext()) and if its there then move the pointer to next element using iterator.next(). Like this way we can move to next element until iterator.hasNext() returns false.

Iterating over list

Advantages of using Iterator

  1. We can remove the elements while iterating over collection.

Limitations of Iterator

  1. The iterator does not add elements to collection.
  2. It does not traverse in backward direction.
  3. It does not do parallel processing as Streams or Spliterator

Difference Between Iterator and Enumeration

IteratorEnumeration
It was introduced in java 1.2. That’s why it not legacyIt was introduced in java 1.0. That’s why it is legacy
It support only reading the element from the collectionIt support only reading and removal of the element from the collection
In collection framework it is used to iterate over only VectorIn collection framework, it is used to iterate over all collection.

IllegalStateException in Iterator

Whenever we call remove on empty list this exception will be throw as

private static void removeFromEmptyList() {
		List<String> list = new ArrayList<String>();
		Iterator<String> iterator = list.iterator();
		iterator.remove();
	}
Exception in thread "main" java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(ArrayList.java:872)
at com.techijournal.collection.TechiJournalIterator.removeFromEmptyList(TechiJournalIterator.java:18)
at com.techijournal.collection.TechiJournalIterator.main(TechiJournalIterator.java:12)

NoSuchElementException Exception in Iterator

When iterator.next() on empty list or when their is not element at next index then this exception is thrown.

private static void nexttoEmptyList() {
		List<String> list = new ArrayList<String>();
		Iterator<String> iterator = list.iterator();
		iterator.next();		
	}
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:862)
at com.techijournal.collection.TechiJournalIterator.nexttoEmptyList(TechiJournalIterator.java:19)
at com.techijournal.collection.TechiJournalIterator.main(TechiJournalIterator.java:13)

Thank’s Note

Thanks for spending you valuable time on this post hope this post was use full to you and you learned something new today. If you like our post please share our post.

Durgesh Kumar

He is the Founder of TechiJournal.com. And have 4+ years of experience as full-stack Java developer. He worked with many reputed product companies and would like to share his experience and knowledge through this blog. He works very hard to provide you with quality content. But as no one is perfect, If you feel that some improvement can be made then feel free to add it in the comment section. We look forward to it.

Leave a Reply