How to Iterate over a Set/HashSet without an Iterator?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Iterating over a set or a HashSet in Java traditionally involves the use of an Iterator, which is a convenient mechanism to traverse through all elements without needing to manage indexes or keys. However, certain situations might require iterating over these collections without using an Iterator explicitly. This may be for clarity, simplicity of code, or specific implementation constraints. Here, we will explore alternative methods to iterate over a Set or HashSet.
Enhanced For-Loop
The most common alternative to using an Iterator to traverse a set is the enhanced for-loop (also known as the "for-each loop"). This loop abstracts away the need for an iterator visible to the programmer, providing a clean and easy-to-read syntax.
Example:
In this example, Java handles the iterator in the background, allowing the code to be more readable and concise. The enhanced for-loop implicitly creates an iterator over the set, and each element in the set is accessible one at a time through the variable num.
Java Streams API
With the introduction of the Streams API in Java 8, another elegant way to iterate over a set arose. Streams provide a high-level abstraction for operations on collections such as maps, sets, lists, etc. Using streams, one can easily perform complex data manipulations including filtering, mapping, or merely iterating with forEach.
Example:
The forEach operation in the Streams API internally handles the iteration, applying the given lambda expression to each element of the set. The Streams API is not only about iteration; it also facilitates a functional approach to handling collections, enabling bulk operations and expressive ways to manipulate data.
Array Conversion
Another manual approach would involve converting the set to an array and then using a traditional for-loop to iterate over the array. This is useful when you need access to array indices or if you need to manipulate the structure while iterating.
Example:
Although this method may seem less efficient due to the overhead of creating an array, it serves well in scenarios requiring traditional loop operations with indices.
Conclusion
While iterators are a powerful tool within Java, they aren't always necessary or desirable. Each method of iterating a set without explicitly using an Iterator in Java serves different needs and scenarios. The choice of method largely depends on the specific requirements of the task, such as readability, efficiency, or the need for additional operations during iteration.
Summary Table
| Method | Use Case | Benefit |
| Enhanced For-Loop | Simple iterations | Clean syntax, abstracts iterator |
| Streams API | Bulk operations Functional programming | Modern, functional syntax Integrated with other stream operations |
| Array Conversion | Index access needed Structure manipulation during iteration | Access to traditional loop benefits like using indices |
Choose the method that best fits your scenario, keeping in mind the trade-offs between readability, efficiency, and ease of use. Each of these methods provides a useful way to deal with collections neatly and effectively in various situations.
Related reading
- How to keep tensorflow session open between predictions? Loading from SavedModel
- How to kill off a pending APM operation
- How to know affected rows in CassandraCQL?
- How to know when Big O is Logarithmic?
- How to iterate over a TreeMap?
- How to iterate through range of Dates in Java?
- How to lazy load images in ListView in Android
- How to let the UI refresh during a long running UI operation

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.