Java HashSet iterator() Example

The iterator() method of java.util.HashSet class will returns iterator over the elements in the hashset in proper sequence

Signature

public Iterator<E> iterator() 

This method returns iterator over the elements in the hashset in proper sequence. Returned iterator will be a fail-fast iterator

Example

The following example shows the usage of java.util.HashSet.iterator() method.

import java.util.Iterator;
import java.util.HashSet;

public class IteratorMethodHashSetExample {
    public static void main(String args[])
    {
        // create an empty HashSet
        HashSet hashSet1 = new HashSet();
        
        // use add() method to add elements to the HashSet
        hashSet1.add("Element1");
        hashSet1.add("Element2");
        hashSet1.add("Element3");
        hashSet1.add("Element4");
        
        //Iterating elements of the HashSet
        System.out.println("Elements of the HashSet");
        Iterator it = hashSet1.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
    }
}

Output

Elements of the HashSet
Element1
Element2
Element3
Element4

Leave a Reply

Your email address will not be published. Required fields are marked *