In this article we will discuss how to Iterate over a HashSet in Java using HashSet.

Fetch Iterator from HashSet

To iterate over a HashSet we will use an Underlying Iterator object of the HashSet.

Fetch the Iterator from a HashSet object use its member function iterator() i.e.

This iterator object will point to the starting of HashSet

How to Use the Iterator

Now with this Iterator object you can traverse over the elements of Set in forward direction using two member function i.e.

HashSet is not an ordered collection i.e. it can store elements in any order based on HashTable and hash codes. But iterator its guaranteed that we can iterate over all elements in a turn.

Now let’s see how to Iterate over a HashSet of String objects and print them one by one i.e.




We can call the size() member function of HashSet to fetch the current size of Hashset.

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.