How to iterate HashSet in Java?
Last Updated :
15 Feb, 2022
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().
Example:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
HashSet<Integer> set = new HashSet<>();
set.add( 10 );
set.add( 20 );
set.add( 10 );
set.add( 50 );
set.add( 50 );
Iterator<Integer> it = set.iterator();
System.out.println(
"Iterate HashSet using iterator : " );
while (it.hasNext()) {
System.out.print(it.next() + " " );
}
}
}
|
Output
Iterate HashSet using iterator :
50 20 10
Method 2: Iterate using for loop
In this method, we iterate HashSet using a simple for loop. Below is the implementation of this approach:
Example:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
HashSet<String> set = new HashSet<>();
set.add( "Hello" );
set.add( "geeks" );
set.add( "on" );
set.add( "geeks" );
set.add( "for" );
set.add( "geeks" );
System.out.println(
"Iterate HashSet using for loop : " );
for (String ele : set) {
System.out.print(ele + " " );
}
}
}
|
Output
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. Below is the implementation of this method:
Example:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
HashSet<String> set = new HashSet<>();
set.add( "Hello" );
set.add( "geeks" );
set.add( "on" );
set.add( "geeks" );
set.add( "for" );
set.add( "geeks" );
System.out.println(
"Iterate HashSet using forEach loop : " );
set.forEach(System.out::println);
}
}
|
Output
Iterate HashSet using forEach loop :
Hello
geeks
for
on
Share your thoughts in the comments
Please Login to comment...