What is the HashSet.iterator() method in Java?

The HashSet.iterator() method is present in the HashSet class inside the java.util package.

This method is used to return an iterator of the same elements as the hash set in an unordered format.

Syntax

Iterator iterator_name = hash_set.iterator()

Parameters

The HashSet.iterator() does not accept any parameters.

Return value

The HashSet.iterator() method returns iterators after iterating over the elements of the HashSet.

Code

Let’s have a look at the code.

import java.io.*;
import java.util.*;
class Main
{
public static void main(String args[])
{
HashSet<Integer> hash_set1 = new HashSet<Integer>();
hash_set1.add(1);
hash_set1.add(8);
hash_set1.add(5);
hash_set1.add(3);
hash_set1.add(0);
Iterator value = hash_set1.iterator();
System.out.println("The iterator values are: ");
while (value.hasNext())
{
System.out.println(value.next());
}
}
}

Explanation

  • In lines 1 and 2, we import the required packages and classes.

  • In line 4, we make a Main class.

  • In line 6, we make a main() function.

  • In line 8, we declare a HashSet of Integer type, i.e., hash_set1.

  • From lines 9 to 13, we add the elements into the HashSet by using the HashSet.add() method.

  • In line 15, we make an object of the Iterator class to use the HashSet.iterator() method.

  • In line 17, we display a message for the upcoming iterator values.

  • In lines 18 to 21, we have a while loop that runs when the iterator object encounters the presence of the next value by using the hasNext() function and displays the every value of iterator.

In this way, we can use the HashSet.iterator() method in Java.

Free Resources