Java HashSet iterator() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

In Java, iterator() returns an Iterator<E> that visits every element of a HashSet exactly once. You ask hasNext() whether another element exists, and next() hands it to you.

The enhanced for loop, for (String s : set), is shorthand for exactly this. Use the iterator itself when you also want to delete the current element with it.remove().

An instance method of java.util.HashSet (class since Java 1.2): a set of unique elements kept in a hash table, with no guaranteed order, one null element allowed, and no thread safety.

Syntax

No arguments; the iterator is the loop control.

Java
Set<String> tags = new HashSet<>();
tags.add("java");
Iterator<String> it = tags.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}
CallWhat it does
it.hasNext()true while there is another element.
it.next()Returns the next element and moves on.
it.remove()Deletes the element that next() just returned.
it.forEachRemaining(action)Runs an action on every element not yet visited (Java 8).

Elements arrive in the order of the internal hash table. That order is not sorted and not the insertion order, and it can change when the set grows.

Library declarations
Java
// java.util.HashSet<E>
public Iterator<E> iterator()

// Declared in Set<E>, Collection<E>, and Iterable<E>

Parameters

ParameterDescription
Noneiterator() takes no parameters.

Return Value

Return ValueDescription
Iterator<E>A fail-fast iterator over the elements, in no particular order.

Compare with Similar Methods

Other ways to visit the elements:

MethodHow it differs
spliterator()A Java 8 iterator that can also split the work in two.
toArray()Copies the elements into an array first.
removeIf(test)Deletes by condition without writing the loop yourself.
remove(o)Deletes one known element, but not during a for-each loop over the same set.

Java Examples

Example 1 — Walk Through a Set with hasNext() and next()

Print each lucky number in the order the iterator returns it.

Java
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetIteratorDemo {
    public static void main(String[] args) {
        Set<Integer> lucky = new HashSet<>();
        lucky.add(7);
        lucky.add(21);
        lucky.add(3);

        Iterator<Integer> it = lucky.iterator();
        while (it.hasNext()) {
            int number = it.next();
            System.out.println("number: " + number);
        }
        System.out.println("has more: " + it.hasNext());
    }
}

How It Works

  1. Ask, then take. hasNext() checks for another element and next() returns it, so the loop body runs three times.
  2. Not sorted, not inserted order. The numbers were added as 7, 21, 3, but they print by bucket position, which puts 21 between 3 and 7.
  3. Unboxing on the way out. next() returns an Integer, which is assigned to an int automatically.
  4. Finished iterator. After the last element hasNext() is false; one more next() would throw NoSuchElementException.

Example 2 — Remove Even Numbers with Iterator.remove()

Delete elements while looping, then misuse remove() by calling it twice in a row.

Java
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetIteratorRemove {
    public static void main(String[] args) {
        Set<Integer> numbers = new HashSet<>();
        for (int i = 1; i <= 8; i++) {
            numbers.add(i);
        }

        Iterator<Integer> it = numbers.iterator();
        while (it.hasNext()) {
            if (it.next() % 2 == 0) {
                it.remove();
            }
        }
        System.out.println("odd numbers: " + numbers);

        Iterator<Integer> again = numbers.iterator();
        again.next();
        again.remove();
        try {
            again.remove();
        } catch (IllegalStateException e) {
            System.out.println("second remove() -> IllegalStateException");
        }
        System.out.println("size now: " + numbers.size());
    }
}

How It Works

  1. Test, then delete. it.next() fetches a number, and when it is even, it.remove() deletes exactly that number from the set.
  2. Safe deletion. Because the removal goes through the iterator, the loop never meets a ConcurrentModificationException; 2, 4, 6, and 8 disappear.
  3. One removal per next(). The second iterator removes the first element it returns (the number 1), and a second remove() without a new next() throws IllegalStateException.
  4. Counting the damage. Four odd numbers minus the removed 1 leaves size 3.

Example 3 — The ConcurrentModificationException Trap

Remove an id inside a for-each loop, which fails, and then remove one correctly with the iterator.

Java
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetIteratorTrap {
    public static void main(String[] args) {
        Set<Integer> ids = new HashSet<>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        ids.add(4);

        try {
            for (Integer id : ids) {
                if (id == 2) {
                    ids.remove(id);
                }
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("remove inside for-each -> ConcurrentModificationException");
        }
        System.out.println("after failed loop: " + ids);

        Iterator<Integer> it = ids.iterator();
        while (it.hasNext()) {
            if (it.next() == 3) {
                it.remove();
            }
        }
        System.out.println("after it.remove(): " + ids);
    }
}

How It Works

  1. Small integers in order. The ids 1 to 4 land in buckets 1 to 4, so the loop reaches 2 after 1 on current JDKs.
  2. The removal itself works. ids.remove(2) deletes the element, but it also bumps the set's modification count behind the iterator's back.
  3. The next step fails. When the hidden iterator is asked for the following element, it notices the changed count and throws ConcurrentModificationException, so 3 and 4 are never visited.
  4. The right way. Removing 3 through it.remove() keeps the iterator informed, so that loop finishes normally and leaves 1 and 4.

Frequently Asked Questions

Use a for-each loop, for (String s : set), or call set.iterator() and loop with hasNext() and next().
In the order of the internal hash table, which is not sorted and not the insertion order. For sorted output copy the set into a TreeSet; for insertion order use LinkedHashSet.
Call it.remove() on the iterator, or use removeIf(). Calling set.remove() inside a for-each loop throws ConcurrentModificationException.
It detects changes made to the set behind its back and throws ConcurrentModificationException instead of returning unpredictable results. The check is best-effort.
It throws NoSuchElementException. Always check hasNext() first.

Next: remove()

Delete one element; returns whether it was there.

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

7 people found this page helpful