Java Intermediate

0% completed

Previous
Next
Iterators in Java

Iterators provide a standard way to traverse through collections without exposing their underlying structure. They are part of the Java Collections Framework and allow you to safely iterate and, if needed, remove elements during traversal. The basic syntax for using an iterator is as follows:

Syntax

Iterator<E> iterator = collection.iterator(); while(iterator.hasNext()) { E element = iterator.next(); // Process the element }

This syntax shows that you first obtain an iterator from a collection using the iterator() method. Then, you repeatedly check for more elements with hasNext(). If an element exists, you retrieve it using next(). This loop continues until all elements have been processed.

Examples

Example 1: Iterating Over an ArrayList

In this example, we create an ArrayList of fruit names and use an iterator to traverse and print each element.

Java
Java

. . . .

Explanation:

  • We create an ArrayList named fruits and add several fruit names.
  • An iterator is obtained from the list, and we traverse through the list using a while loop that checks hasNext().
  • Each element is retrieved using next() and printed.

Example 2: Removing Elements Using Iterator's remove() Method

In this example, we demonstrate how to remove elements from an ArrayList while iterating over it using the iterator's remove() method.

Java
Java

. . . .

Explanation:

  • We create an ArrayList named items and add several strings, including duplicates.
  • An iterator is obtained from the list.
  • While traversing the list, if an element equals "Pencil", the iterator's remove() method is called to delete that element.
  • Finally, the updated list is printed, showing that all "Pencil" entries have been removed.

Iterators offer a safe and uniform way to traverse and manipulate collections in Java. In the examples above, we saw how to iterate over an ArrayList using the hasNext() and next() methods, and how to remove elements during iteration using the remove() method. This approach encapsulates the traversal logic, allowing you to focus on processing each element without exposing the internal structure of the collection.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next