Java Iterator

Java Iterator is an interface used to traverse a collection of elements. It provides a way to access elements in a collection without exposing the underlying implementation. In this blog, we will explore Java Iterator in detail, including how to declare and use it, and provide example code snippets to illustrate each concept.

Declaring a Java Iterator:

To declare a Java Iterator, you need to import the java.util.Iterator interface and create an instance of it. Here is an example:

import java.util.Iterator;

Iterator<String> iterator = list.iterator();

In the above example, we declare an Iterator called iterator of type String.

Traversing a Java Iterator:

To traverse a Java Iterator, you can use the hasNext() and next() methods. Here is an example:

while (iterator.hasNext()) {
   String element = iterator.next();
   System.out.println(element);
}

In the above example, we use a while loop to iterate over the Iterator and print each element using the System.out.println() method.

Removing Elements from a Java Iterator:

To remove elements from a Java Iterator, you can use the remove() method. Here is an example:

iterator.remove();

In the above example, we remove the current element from the Iterator.

Using Java Iterator with Collections:

Java Iterator is commonly used with collections such as ArrayList and LinkedList. Here is an example of using Iterator with an ArrayList:

ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

Iterator<String> iterator = list.iterator();

while (iterator.hasNext()) {
   String element = iterator.next();
   System.out.println(element);
}

In the above example, we create an ArrayList, add three elements to it, and then use an Iterator to traverse the list and print each element.

Conclusion:

Java Iterator is an essential tool for traversing collections of elements. It provides a way to access elements without exposing the underlying implementation. In this blog, we explored how to declare and use a Java Iterator, including how to traverse a collection of elements, remove elements from an Iterator, and use an Iterator with collections such as ArrayList and LinkedList. If you need to traverse a collection of elements, consider using a Java Iterator.