Home Java LinkedList Methods iterator() Java LinkedList iterator() Method Definition In Java, iterator() returns an Iterator that visits the elements of the LinkedList from the first to the last. You ask hasNext() whether there is another element, and next() to get it.
The iterator also has remove(), which deletes the element that next() just returned. This is the safe way to remove elements while looping. A for-each loop uses an iterator behind the scenes.
An instance method of java.util.LinkedList (since Java 1.2): call it on a LinkedList object. Add import java.util.LinkedList; at the top of your file. It is declared by Iterable, Collection and List, and LinkedList implements it.
Syntax Ask for the iterator, then loop with hasNext and next.
LinkedList<String> list = new LinkedList<>(Arrays.asList("A", "B", "C"));
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String item = it.next();
System.out.println(item);
} Call What it does list.iterator()Creates an iterator that starts before the first element. it.hasNext()true if another element is available.it.next()Returns the next element and moves forward. it.remove()Removes the element last returned by next().
Every call to iterator() creates a new, independent iterator that starts at the beginning.
Library declarations // java.util.LinkedList
public Iterator<E> iterator()
// the list's listIterator(0) is returned Parameters Parameter Description None iterator() takes no parameters.
Return Value Return Value Description Iterator<E>An iterator over the elements in order, from first to last.
Important
The iterator is fail-fast . If the list is changed in any other way during the walk, for example with list.remove(...) inside a for-each loop, the next call to next() throws ConcurrentModificationException. Use it.remove() instead. Calling next() after the last element throws NoSuchElementException, and calling remove() twice in a row throws IllegalStateException.
Compare with Similar Methods Ways to walk a list:
Java Examples 1. Walk the list 2. Remove while looping 3. Common exceptions Example 1 — Visit Every Element with an Iterator Walk a list of colors with hasNext and next, and count them.
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListIteratorDemo {
public static void main(String[] args) {
LinkedList<String> colors = new LinkedList<>();
colors.add("red");
colors.add("green");
colors.add("blue");
Iterator<String> it = colors.iterator();
int count = 0;
while (it.hasNext()) {
String color = it.next();
count++;
System.out.println(count + ": " + color);
}
System.out.println("has next now: " + it.hasNext());
}
} 1: red
2: green
3: blue
has next now: false How It Works The iterator starts before the first element. Nothing has been returned yet.hasNext guards next. The loop only calls next() when another element is waiting.Elements arrive in list order. The loop prints red, green and blue, with a running count.At the end. After the third element, hasNext() returns false, so the loop stops.Example 2 — Remove Elements Safely While Iterating Delete all odd numbers from a list with it.remove().
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListIteratorRemove {
public static void main(String[] args) {
LinkedList<Integer> nums = new LinkedList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
int n = it.next();
if (n % 2 != 0) {
it.remove();
}
}
System.out.println("evens only: " + nums);
System.out.println("size: " + nums.size());
}
} evens only: [2, 4, 6]
size: 3 How It Works Seven numbers. Four of them are odd: 1, 3, 5 and 7.next returns the current element. The test n % 2 != 0 is true for the odd ones.it.remove deletes it. It removes the element that next() just returned, and the iterator carries on without any error.Only evens are left. The list is 2, 4, 6, and the size is 3.Example 3 — See the Exceptions an Iterator Can Throw Remove during a for-each loop, call remove() too early, and call next() past the end.
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
public class LinkedListIteratorErrors {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>(Arrays.asList("a", "b", "c"));
try {
for (String s : list) {
list.remove(s);
}
} catch (RuntimeException e) {
System.out.println("for-each + list.remove -> " + e.getClass().getSimpleName());
}
LinkedList<String> fresh = new LinkedList<>(Arrays.asList("x", "y"));
Iterator<String> it = fresh.iterator();
try {
it.remove();
} catch (IllegalStateException e) {
System.out.println("remove before next -> IllegalStateException");
}
it.next();
it.next();
try {
it.next();
} catch (NoSuchElementException e) {
System.out.println("next past the end -> NoSuchElementException");
}
}
} for-each + list.remove -> ConcurrentModificationException
remove before next -> IllegalStateException
next past the end -> NoSuchElementException How It Works Changing the list behind the iterator's back. Inside the for-each loop, list.remove(s) changes the list, but the hidden iterator does not know.Fail-fast check. On the next next() the iterator notices the change and throws ConcurrentModificationException.remove needs a next first. Calling it.remove() before any next() has nothing to remove, so it throws IllegalStateException.Past the end. After both elements have been read, a third next() throws NoSuchElementException.Frequently Asked Questions How do I iterate over a LinkedList in Java? Use a for-each loop, or get an iterator with list.iterator() and loop with hasNext() and next().
How do I remove elements from a LinkedList while looping? Use the iterator and call it.remove(), or use list.removeIf(...) on Java 8 and later. Do not call list.remove() inside a for-each loop.
Why do I get ConcurrentModificationException? The list was changed while an iterator was walking it, in a way the iterator did not do itself. Remove through the iterator instead.
What is the difference between iterator() and listIterator()? listIterator can move backward and can add and replace elements. iterator only moves forward and can remove.
Is iterating a LinkedList fast? Yes. The iterator moves from node to node, so a full pass takes time proportional to the size. This is much faster than calling get(i) in a loop.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
13 people found this page helpful
Helpful Share Copy link Suggestion