Home »
Java programming language
Java HashSet iterator() Method with Example
HashSet Class iterator() method: Here, we are going to learn about the iterator() method of HashSet Class with its syntax and example.
Submitted by Preeti Jain, on March 05, 2020
HashSet Class iterator() method
- iterator() method is available in java.util package.
- iterator() method is used to iterate all the elements that exist in this HashSet by using iterator () method.
- iterator() method is a non-static method, it is accessible with the class object only, and if we try to access the method with the class name then we will get an error.
- iterator() method does not throw an exception at the time of iterating HashSet elements.
Syntax:
public Iterator iterator();
Parameter(s):
- It does not accept any parameter.
Return value:
The return type of the method is Iterator, it returns an Iterator over the objects exist in this HashSet.
Example:
// Java program to demonstrate the example
// of Iterator iterator () method of HashSet
import java.util.*;
public class IteratorOfHashSet {
public static void main(String[] args) {
// Instantiates a HashSet object
HashSet < String > hs = new HashSet < String > ();
// By using add() method is to add
// the given object of this
// HashSet
hs.add("C");
hs.add("C++");
hs.add("JAVA");
hs.add("PHP");
hs.add("SFDC");
// Display HashSet
System.out.println("HashSet: " + hs);
// By using iterator() method is to
// iterate the HashSet elements in an
// increasing order
System.out.println("hs.iterator(): ");
for (Iterator itr = hs.iterator(); itr.hasNext();)
System.out.println(itr.next());
}
}
Output
HashSet: [JAVA, C++, C, SFDC, PHP]
hs.iterator():
JAVA
C++
C
SFDC
PHP