Java Iterator — Free Java Tutorial
Learn Java Iterator in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn Java Iterator in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
Java Iterator in Java
Iterator<T> defines a standard way to traverse a collection: hasNext() checks if more elements remain, next() returns the next element, remove() removes the last returned element.
Iterable<T> (implemented by all collections) enables the enhanced for-each loop. Any class implementing Iterable must return an Iterator from iterator().
The key advantage of Iterator.remove() is safe removal while iterating — removing from a collection during for-each throws ConcurrentModificationException.
ListIterator extends Iterator with bidirectional traversal (previous(), hasPrevious()) and allows set() and add() operations during iteration.
Java Iterator — Syntax
// Iterator usage
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (shouldRemove(s)) it.remove(); // safe removal
}
// For-each uses Iterable internally
for (String s : list) { ... }
// Custom Iterable class
class Range implements Iterable<Integer> {
Learn Java Iterator step by step with Syllab's free interactive Java tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Java course →