Home Java TreeSet Methods iterator() Java TreeSet iterator() Method Definition In Java, iterator() returns an Iterator<E> that visits the elements of a TreeSet in ascending sorted order (from first() to last()).
An enhanced for loop uses iterator() behind the scenes, while calling iterator() explicitly gives you it.remove()βthe safe way to delete elements while looping without triggering ConcurrentModificationException.
An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe .
Syntax Obtain an iterator and loop with hasNext() and next().
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String item = it.next();
if (item.startsWith("OLD-")) {
it.remove(); // safe removal during loop
}
} Call What it does set.iterator()Returns an ascending iterator starting before the first element. it.hasNext()Returns true while unvisited elements remain. it.next()Advances and returns the next sorted element. it.remove()Removes the element last returned by next().
A TreeSet iterator cannot walk backward and has no ListIterator; use descendingIterator() to step from largest to smallest.
Library declarations // java.util.TreeSet<E>
public Iterator<E> iterator()
// java.util.Iterator<E>
boolean hasNext()
E next()
void remove() Parameters Parameter Description None iterator() takes no parameters.
Return Value Return Value Description Iterator<E>A fail-fast iterator traversing elements in ascending order.
Important
The iterator is fail-fast : modifying the TreeSet directly (except through it.remove()) causes the next next() or remove() call to throw ConcurrentModificationException (best-effort). Calling next() past the end throws NoSuchElementException, and calling it.remove() before next() or twice in a row throws IllegalStateException.
Compare with Similar Methods Ways to traverse a TreeSet:
Java Examples 1. Ascending walk 2. Safe it.remove() 3. Fail-fast and IllegalState Example 1 — Walk Sorted Student Names With hasNext() and next() Iterate through a roster in alphabetical order and confirm hasNext() turns false once exhausted.
import java.util.Arrays;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetIteratorRollCall {
public static void main(String[] args) {
TreeSet<String> students = new TreeSet<>(Arrays.asList("Zara", "Eli", "Mina", "Eli"));
Iterator<String> it = students.iterator();
int num = 1;
while (it.hasNext()) {
System.out.println(num + ". " + it.next());
num++;
}
System.out.println("more remaining? " + it.hasNext());
}
} 1. Eli
2. Mina
3. Zara
more remaining? false How It Works Deduplicated sorted stream. The duplicate "Eli" collapsed on insert, so the iterator visits Eli, Mina, then Zara.Check before stepping. hasNext() ensures next() never runs past the end and avoids NoSuchElementException.Single-pass cursor. Once hasNext() returns false, obtain a fresh students.iterator() to loop again.Example 2 — Safely Remove Expired Codes While Iterating Walk sorted discount codes and remove every code starting with "EXP-" using it.remove().
import java.util.Arrays;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetIteratorPrune {
public static void main(String[] args) {
TreeSet<String> promos = new TreeSet<>(Arrays.asList("VIP20", "EXP-01", "SAVE10", "EXP-09"));
Iterator<String> it = promos.iterator();
int removed = 0;
while (it.hasNext()) {
if (it.next().startsWith("EXP-")) {
it.remove();
removed++;
}
}
System.out.println("removed: " + removed);
System.out.println("active promos: " + promos);
}
} removed: 2
active promos: [SAVE10, VIP20] How It Works Ascending alphabetical scan. Because "EXP-01" and "EXP-09" precede "SAVE10", the iterator reaches both expired codes first.Iterator-driven deletion. Calling it.remove() deletes the entry safely and updates the iterator's expected modification count.No ConcurrentModificationException. Both expired promos are pruned cleanly, leaving [SAVE10, VIP20].Example 3 — Fail-Fast ConcurrentModificationException and IllegalStateException See ConcurrentModificationException after modifying the set directly, and IllegalStateException when calling remove() too early.
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetIteratorFailFast {
public static void main(String[] args) {
TreeSet<Integer> ids = new TreeSet<>(Arrays.asList(10, 20, 30));
Iterator<Integer> it = ids.iterator();
System.out.println("first: " + it.next());
ids.add(25);
try {
it.next();
} catch (ConcurrentModificationException e) {
System.out.println("after set.add: " + e.getClass().getSimpleName());
}
Iterator<Integer> fresh = ids.iterator();
try {
fresh.remove();
} catch (IllegalStateException e) {
System.out.println("remove before next: " + e.getClass().getSimpleName());
}
}
} first: 10
after set.add: ConcurrentModificationException
remove before next: IllegalStateException How It Works Concurrent edit detected. Adding 25 directly to ids invalidates the active iterator it, so the next step fails fast.Remove needs a current element. Calling remove() on fresh before calling next() throws IllegalStateException.Best-effort safety net. Never rely on ConcurrentModificationException for control flow; keep direct edits separate from loops.Frequently Asked Questions In what order does TreeSet iterator() return elements? Always in ascending order according to natural ordering or the custom Comparator passed to the TreeSet.
How do I safely remove elements while iterating a TreeSet? Create an explicit Iterator, advance with it.next(), and call it.remove(), or use set.removeIf(condition).
Why did I get ConcurrentModificationException during a for-each loop? You added or removed an element directly on the TreeSet while the loop iterator was still active.
Can a TreeSet Iterator move backward? No. Call descendingIterator() to step from largest to smallest instead.
What happens if I call next() after the last element? It throws NoSuchElementException. Always check it.hasNext() before calling it.next().
Next: last() Read the largest (highest) element without removing it; throws if empty.
last() tutorial → 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.
11 people found this page helpful
Helpful Share Copy link Suggestion