How to Iterate HashSet in Java: Simple Examples and Tips
To iterate over a
HashSet in Java, you can use a for-each loop, an Iterator, or the forEach method with a lambda expression. These methods allow you to access each element in the set one by one.Syntax
Here are common ways to iterate a HashSet:
- For-each loop: Simple and readable way to access each element.
- Iterator: Gives more control, allows safe removal during iteration.
- forEach method: Uses lambda expressions introduced in Java 8 for concise iteration.
java
HashSet<Type> set = new HashSet<>(); // For-each loop for (Type item : set) { // use item } // Iterator Iterator<Type> iterator = set.iterator(); while (iterator.hasNext()) { Type item = iterator.next(); // use item } // forEach method (Java 8+) set.forEach(item -> { // use item });
Example
This example shows how to create a HashSet of strings and iterate over it using all three methods.
java
import java.util.HashSet; import java.util.Iterator; public class HashSetIterationExample { public static void main(String[] args) { HashSet<String> fruits = new HashSet<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); System.out.println("Using for-each loop:"); for (String fruit : fruits) { System.out.println(fruit); } System.out.println("\nUsing Iterator:"); Iterator<String> iterator = fruits.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } System.out.println("\nUsing forEach method:"); fruits.forEach(fruit -> System.out.println(fruit)); } }
Output
Using for-each loop:
Apple
Banana
Cherry
Using Iterator:
Apple
Banana
Cherry
Using forEach method:
Apple
Banana
Cherry
Common Pitfalls
Some common mistakes when iterating a HashSet include:
- Trying to access elements by index (HashSet does not support indexing).
- Modifying the set directly inside a for-each loop, which can cause
ConcurrentModificationException. - Not using an
Iteratorwhen removing elements during iteration.
Always use an Iterator if you need to remove elements while looping.
java
import java.util.HashSet; import java.util.Iterator; public class HashSetRemoveExample { public static void main(String[] args) { HashSet<String> set = new HashSet<>(); set.add("One"); set.add("Two"); set.add("Three"); // Wrong: Removing inside for-each loop causes error // for (String s : set) { // if (s.equals("Two")) { // set.remove(s); // Causes ConcurrentModificationException // } // } // Right: Use Iterator to remove safely Iterator<String> it = set.iterator(); while (it.hasNext()) { if (it.next().equals("Two")) { it.remove(); } } System.out.println(set); // Output: [One, Three] } }
Output
[One, Three]
Quick Reference
Remember these tips when iterating a HashSet:
- Use for-each loop for simple read-only iteration.
- Use Iterator when you need to remove elements safely during iteration.
- Use forEach method with lambda for concise code in Java 8 and later.
- HashSet does not maintain order, so iteration order is unpredictable.
Key Takeaways
Use a for-each loop to easily iterate over all elements in a HashSet.
Use an Iterator to safely remove elements while iterating.
The forEach method with lambda expressions offers concise iteration in Java 8+.
HashSet does not support indexing or ordered access.
Avoid modifying the HashSet directly inside a for-each loop to prevent errors.