Open In App

Java HashSet iterator() Method

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
1 Like
Like
Report

The HashSet iterator() method in Java is used to return an iterator that can be used to iterate over the elements in a HashSet. HashSet does not maintain any specific order of its elements, so the elements are returned in random order when iterated over. The iterator() method provides a way to traverse the elements in the set, allowing you to access them one by one.

Example 1: Iterating over a HashSet of Integers


Output
HashSet: [20, 10, 30]
The iterator values are: 20 10 30 

Note: The order of elements in a HashSet is not guaranteed and can vary each time the program runs, as shown in the output.

Syntax of HashSet iterator() Method

public Iterator<E> iterator();

Return Type: This method returns an Iterator object to traverse the elements in the collection one by one.

Example 2: Iterating over a HashSet of Custom Objects

In this example, we will demonstrate how to store custom object "Employee" in a HashSet and iterate through them using an iterator.


Output
Value: [ 35, Geek5 ] 
Value: [ 10, Geek1 ] 
Value: [ 2, Geek20 ] 

Similar Reads