Java ProgramsCollectionsIterator Example

Iterator Example in Java

beginner·  Collections  ·  Iterator

Problem

An Iterator gives explicit, step-by-step access to a collection's elements through hasNext() and next(), and is the only safe way to remove elements while a loop over the collection is still in progress.

Given a list of numbers, remove every one divisible by 15 while iterating, using an Iterator instead of a for-each loop.

Input
[10, 15, 20, 25, 30], remove multiples of 15
Output
[10, 20, 25]

Java Program

Java
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IteratorDemo { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(15); numbers.add(20); numbers.add(25); numbers.add(30); Iterator<Integer> it = numbers.iterator(); while (it.hasNext()) { int value = it.next(); if (value % 15 == 0) { it.remove(); // safe removal during iteration — uses the iterator, not the list } } System.out.println(numbers); } }

Output

[10, 20, 25]

Core Logic

Walking the list with an explicit Iterator, instead of a for-each loop, is what allows calling remove() safely mid-traversal without disturbing the iteration itself.

How It Works
  1. 1numbers.iterator() returns an Iterator<Integer> positioned before the first element.
  2. 2hasNext() checks whether another element remains, and next() advances to it and returns its value.
  3. 3it.remove() deletes the element next() just returned — this is the iterator's own remove method, not the list's.
  4. 4The loop continues correctly after each removal, since the iterator tracks its own position internally as elements shift.
Out of [10, 15, 20, 25, 30], both 15 and 30 are divisible by 15 and get removed, leaving [10, 20, 25].
💡

Key Point: Calling numbers.remove(...) directly on the list instead of on the iterator would corrupt the iteration and throw an exception — this exact failure is what the dedicated Fail-Fast Iterator page demonstrates.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: The iterator visits each of the n elements once; on an ArrayList, each remove() call also shifts every later element down by one, so removing many elements can push the total work toward O(n²), though a single pass with only a few removals stays close to O(n).

Key Concepts

IteratorhasNext()next()remove()

Related Programs