Java Iterator

Java Iterator interface belongs to java.util package and it is a part of Collection framework. Iterator interface allows us to iterate over collection of different class objects such as ArrayList, HashSet etc.

Iterator supports add and remove operations only.

Limitations of Iterator:

  1. Iterator works only in forward direction.
  2. Add and update of new element is not allowed.

Syntax:

Iterator<T> iterator;

Iterator Methods:

hasNext() → returns true if iterator has more elements.

next() → returns next element if iterator has more elements.

remove() → remove the element from iterator. There is no return type of this method. 

remove method throws two below exceptions:

  1. UnsupportedOperationException
  2. IllegalStateException

Example:

Below is the example to iterate through ArrayList.

Note: I always try to make things easy and simple, please read comments while reading code snippet will help to understand better.

Iterator remove() method:

Remove() method will help us to remove element from list.

Custom Iterator:

Custom iterator will help us to iterate over custom collection class.

Follow below steps to create custom iterator:

  1. Create bean class having parameterized constructor or setter-getter methods.
  2. Create One more custom collection class like Students and implement same with Iterator interface and override iterator() method to iterate over students collection defined in Students class.
  3. Create for loop and iterate through Students custom collection.

Difference Between Iterator and ListIterator

Imran Khan

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan