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());
}
Call
What 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
Parameter
Description
None
iterator() takes no parameters.
Return Value
Return Value
Description
Iterator<E>
A fail-fast iterator over the elements, in no particular order.
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());
}
}
Output
number: 3
number: 21
number: 7
has more: false
HashSet iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
Ask, then take.hasNext() checks for another element and next() returns it, so the loop body runs three times.
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.
Unboxing on the way out.next() returns an Integer, which is assigned to an int automatically.
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());
}
}
HashSet iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
Test, then delete.it.next() fetches a number, and when it is even, it.remove() deletes exactly that number from the set.
Safe deletion. Because the removal goes through the iterator, the loop never meets a ConcurrentModificationException; 2, 4, 6, and 8 disappear.
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.
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);
}
}
Output
remove inside for-each -> ConcurrentModificationException
after failed loop: [1, 3, 4]
after it.remove(): [1, 4]
HashSet iteration order is not guaranteed. This is the typical output on OpenJDK 8–21; other JDKs or versions may print the entries in a different order.
How It Works
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.
The removal itself works.ids.remove(2) deletes the element, but it also bumps the set's modification count behind the iterator's back.
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.
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.