HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.
There are three simple ways to iterate over a HashSet, which is the following :
- Using Iterator
- Without using Iterator (using for loop)
- Using for-each loop
Method 1: Iterator method
In this method, we iterate HashSet with the help of iterator. First, we make an iterator to iterate HashSet with the help of the iterator() method in Java.
// Create a iterator of integer type to iterate HashSet Iterator<Integer> it = set.iterator();
And then iterate HashSet with the help of hasNext() and Next() method in Java. Where hasNext() method check whether HashSet has elements or not and, Next() method access the data of HashSet.
Note: Use Next() method only one time after hasNext().
Iterate HashSet using iterator : 50 20 10
Method 2: Iterate using for loop
In this method, we iterate HashSet using a simple for loop. Bellow is the implementation of this approach:
Iterate HashSet using for loop : Hello geeks for on
Method 3: Using forEach() method
In this method, we iterate HashSet using forEach() loop in Java. Bellow is the implementation of this method:
Iterate HashSet using forEach loop : Hello geeks for on
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.