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.
// Create a HashSet of String HashSet<String> setOfStrs = new HashSet<>(); // Fetch an Iterator object from HashSet Object Iterator<String> it = setOfStrs.iterator();
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.
// It will check if next element exist or not boolean hasNext(); // It returns the next element from set E next();
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.
Frequently Asked:
- How to Merge an Array in a HashSet in Java
- How to Merge two HashSets in Java
- How to convert a HashSet into an array in Java
- How to Search for an element in HashSet in Java
Now let’s see how to Iterate over a HashSet of String objects and print them one by one i.e.
package com.thispointer.java.collections.hashsets; import java.util.HashSet; import java.util.Iterator; public class Example1 { public static void main(String[] args) { // Create a HashSet of String HashSet<String> setOfStrs = new HashSet<>(); //Add String Objects to HashSet setOfStrs.add("hello"); setOfStrs.add("abc"); setOfStrs.add("time"); setOfStrs.add("Hi"); //Try to Add a duplicate element setOfStrs.add("abc"); //Size of HashSet System.out.println("Set Size is = " + setOfStrs.size()); // Fetch an Iterator object from HashSet Object Iterator<String> it = setOfStrs.iterator(); // Iterate till next element exists while(it.hasNext()) { // Fetch the next element String data = it.next(); System.out.println(data); } } }
Output:
Set Size is = 4 Hi abc hello time
[showads ad=inside_post]
We can call the size() member function of HashSet to fetch the current size of Hashset.