What is an Iterator in Java?

What is an Iterator?

An Iterator is a special object used to access elements of a collection one by one, such as a List, Set, or any other collection.

It helps you navigate through a collection without knowing how that collection is implemented internally.

Imagine it is a TV remote; you don’t need to open the TV to change channels; you just use the remote to move one step at a time.

The Iterator is part of java.util package and is a key part of the Java Collections Framework.

Why We Use an Iterator in Java?

Iterators provide us with several practical benefits:

  • Sequential Access: It allows you to move through the elements of a collection one by one, making traversal simple and controlled.
  • Safe Removal of Elements: You can remove elements during iteration using the remove() method of Iterator, which avoids errors like ConcurrentModificationException.
  • Hides Internal Structure: You don’t need to know how the collection stores its data (like an array, linked list, etc.). You only focus on accessing elements.

Iterator Interface in Java

The Iterator interface defines three methods:

1) hasNext(): This method checks if there are any more elements left to iterate over in the collection.
It returns true if another element exists; otherwise false.

Syntax:

boolean hasNext();

Example use:

if (iterator.hasNext()) {
    // Safe to call next()
}

2) next(): This method returns the next element in the collection during iteration. Every time you call next(), the iterator moves forward to the next item.

Syntax:

E next();

Example use:

String name = iterator.next();
System.out.println(name);
  • next() gives you the current item and moves the pointer to the next one, just like reading the next line of a list.

3) remove(): This method removes the last element returned by the next() method from the collection. Syntax:

void remove();

Example use:

if (name.equals("Bob")) {
    iterator.remove(); // Safely removes "Bob"
}

Example 1: Iterating Through an ArrayList

Let’s we create one example that shows how to use an Iterator to loop through a list of strings.

import java.util.*;

public class IteratorExample {
public static void main(String[] args) {
// Creating a list of fruits
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

// Getting an iterator for the list
Iterator<String> iterator = fruits.iterator();

System.out.println("Fruits in the list:");

// Looping through the list using Iterator
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
}
}
}

Output:

Fruits in the list:
Apple
Banana
Cherry
  • This program first creates an ArrayList and containing fruit names. Then it gets an Iterator from the list.
  • Using a while loop, it checks if there’s another element using hasNext(),
    and retrieves each element using next().

Example 2: Removing Elements During Iteration

Sometimes you need to remove certain elements while iterating, for example, removing numbers that meet a specific condition.

import java.util.*;

public class RemoveExample {
public static void main(String[] args) {
// Creating a list of numbers
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

// Getting an iterator for the list
Iterator<Integer> iterator = numbers.iterator();

System.out.println("Original List: " + numbers);

// Removing even numbers during iteration
while (iterator.hasNext()) {
int num = iterator.next();
if (num % 2 == 0) {
iterator.remove(); // Safe removal using iterator
}
}

// Displaying the updated list
System.out.println("Updated List (after removing even numbers): " + numbers);
}
}

Output:

Original List: [1, 2, 3, 4, 5]
Updated List (after removing even numbers): [1, 3, 5]

Iterator and ListIterator in Java

both Iterator and ListIterator are used to traverse elements. However, there are a few key differences between them based on how they work, what they support, and which collections they can be used with.

  • ListIterator in Java: The ListIterator is a more powerful version of the Iterator. It works only with lists (such as ArrayList and LinkedList), but provides extra capabilities, including moving backwards, adding, or modifying elements during iteration.

Example: ListIterator

import java.util.*;

public class ListIteratorExample {
public static void main(String[] args) {
// Creating a list of names
List<String> names = new ArrayList<>(Arrays.asList("Riya", "Arjun", "Meera"));

// Getting a ListIterator for the list
ListIterator<String> listIterator = names.listIterator();

System.out.println("Traversing Forward:");
// Moving forward through the list
while (listIterator.hasNext()) {
String name = listIterator.next();
System.out.println(name);
}

System.out.println("\nTraversing Backward:");
// Moving backward through the list
while (listIterator.hasPrevious()) {
String name = listIterator.previous();
System.out.println(name);
}
}
}

Output:

Traversing Forward:
Riya
Arjun
Meera

Traversing Backward:
Meera
Arjun
Riya

Also Learn Important Topics of Java

Leave a Comment