Java TreeSet iterator() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

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().

Java
Iterator<String> it = set.iterator();
while (it.hasNext()) {
    String item = it.next();
    if (item.startsWith("OLD-")) {
        it.remove();   // safe removal during loop
    }
}
CallWhat 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
// java.util.TreeSet<E>
public Iterator<E> iterator()

// java.util.Iterator<E>
boolean hasNext()
E next()
void remove()

Parameters

ParameterDescription
Noneiterator() takes no parameters.

Return Value

Return ValueDescription
Iterator<E>A fail-fast iterator traversing elements in ascending order.

Compare with Similar Methods

Ways to traverse a TreeSet:

MethodHow it differs
descendingIterator()Walks the elements from largest to smallest instead.
descendingSet()Gives a full reversed view (with its own iterator()).
spliterator()Java 8+ late-binding spliterator used by streams.
ArrayList.iterator()Visits list elements in index order rather than sorted order.

Java Examples

Example 1 — Walk Sorted Student Names With hasNext() and next()

Iterate through a roster in alphabetical order and confirm hasNext() turns false once exhausted.

Java
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());
    }
}

How It Works

  1. Deduplicated sorted stream. The duplicate "Eli" collapsed on insert, so the iterator visits Eli, Mina, then Zara.
  2. Check before stepping. hasNext() ensures next() never runs past the end and avoids NoSuchElementException.
  3. 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().

Java
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);
    }
}

How It Works

  1. Ascending alphabetical scan. Because "EXP-01" and "EXP-09" precede "SAVE10", the iterator reaches both expired codes first.
  2. Iterator-driven deletion. Calling it.remove() deletes the entry safely and updates the iterator's expected modification count.
  3. 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.

Java
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());
        }
    }
}

How It Works

  1. Concurrent edit detected. Adding 25 directly to ids invalidates the active iterator it, so the next step fails fast.
  2. Remove needs a current element. Calling remove() on fresh before calling next() throws IllegalStateException.
  3. Best-effort safety net. Never rely on ConcurrentModificationException for control flow; keep direct edits separate from loops.

Frequently Asked Questions

Always in ascending order according to natural ordering or the custom Comparator passed to the TreeSet.
Create an explicit Iterator, advance with it.next(), and call it.remove(), or use set.removeIf(condition).
You added or removed an element directly on the TreeSet while the loop iterator was still active.
No. Call descendingIterator() to step from largest to smallest instead.
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

Mari Selvan M P
Mari Selvan M P πŸ”—

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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