Java Iterator

</>Coding Tamilan.← Java course & curriculum
Java Masterclass · Lesson 44 / 50 · English

Java Iterator

Visit elements with an explicit cursor.

Step-by-step explanationsRunnable JavaPractice + answer

Read this topic in தமிழ் ↗.

By the end of this lesson, you can…

  • Explain the key idea behind Iterator.
  • Read and run a complete example, then predict what changes.
  • Recognize the topic-specific mistake discussed below.
01 / The concept

Understand the idea

An Iterator separates traversal from the collection implementation. hasNext checks whether another element exists; next consumes it. When supported, iterator.remove removes the most recently returned element in a controlled way.

02 / Step by step

Explore the details

Java Iterator

An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet.

It is called an "iterator" because "iterating" is the technical term for looping.

To use an Iterator, you must import it from the java.util package.

Getting an Iterator

The iterator() method can be used to get an Iterator for any collection:

Looping Through a Collection

To loop through a collection, use the hasNext() and next() methods of the Iterator:

Removing Items from a Collection

Iterators are designed to easily change the collections that they loop through. The remove() method can remove items from a collection while looping.

Note: Trying to remove items using a for loop or a for-each loop would not work correctly because the collection is changing size at the same time that the code is trying to loop.

The var Keyword with Iterators

You can also use the var keyword with iterators. This avoids repeating the long type name Iterator<String>, since the compiler already knows the type from the collection.

This makes code shorter, but many developers still use the full type for clarity. Since var is valid from Java version 10, you may see it in other code, so it's good to know that it exists:

Java reference fragmentJAVA
ArrayList<String> cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");

// Get an iterator and loop
Iterator<String> it = cars.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}
// Volvo, BMW, Ford

// Safe removal during iteration
ArrayList<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5));
Iterator<Integer> iter = nums.iterator();
while (iter.hasNext()) {
    if (iter.next() < 3) iter.remove();  // removes 1 and 2
}
System.out.println(nums);  // [3, 4, 5]

Here, var makes the iterator declaration shorter, but the actual type is still Iterator<String>.

03 / Read and predict

A complete runnable example

This complete Main.java program focuses on the lesson idea. Reference fragments above may demonstrate individual statements; this example includes the imports, entry point, and supporting types it needs.

Main.java · complete runnable exampleJAVA
import java.util.*;
public class Main {
    public static void main(String[] args) throws Exception {
        ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
        Iterator<Integer> iterator = numbers.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() % 2 == 0) iterator.remove();
        }
        System.out.println(numbers);
    }
}
Predict first. Then reveal the expected output / வெளியீடு
[1, 3]

The output shown was checked by running this complete example. Trace the executed statements in order, then compare with your run.

04 / Learn by changing

Change it. Run it. Understand it.

Load this lesson example into the editor. Change one value or statement, predict the result, then press RUN to execute Java.

Open Java editor ↗
After the editor loads, choose Load this lesson example, then press RUN.

Powered by OneCompiler. Code you run is sent to OneCompiler for execution. For Scanner examples, supply input in the editor I/O panel; for file examples, files exist in its execution environment.

05 / Your turn

Make it your own

Practice challenge

Change the condition to remove odd values instead.

Reveal the answer and reasoning / விடை

The remaining list is [2, 4].

One mistake to avoid: Do not structurally modify the list directly while traversing it with its iterator. Fail-fast checks are diagnostic, not a concurrency guarantee.

Your learning checkpoint

  • Explain the example without reading the output first.
  • Make the change requested in the practice task.
  • Describe why the result changed—or why compilation failed.

Ready to move on? Follow the next lesson in course order, or return to the curriculum to review a prerequisite.

Coding Tamilan · Understand the idea. Try the code. Build the habit.