Java Utility Library

Java HashSet - iterator() Method



The java.util.HashSet.iterator() method returns an iterator over the elements in the set. The elements are returned in no particular order.

Syntax

public Iterator<E> iterator()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns an iterator over the elements in the set.

Exception

NA

Example:

In the example below, the java.util.HashSet.iterator() method returns an iterator which is further used to display the content of the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating hash set
    HashSet<Integer> MySet = new HashSet<Integer>();

    //populating hash set
    MySet.add(10);
    MySet.add(20);
    MySet.add(30);
    MySet.add(40);

    //create an iterator
    Iterator it = MySet.iterator();

    //printing hash map
    System.out.print("MySet contains: "); 
    while(it.hasNext()) 
      System.out.print(it.next()+ " ");  
  }
}

The output of the above code will be:

MySet contains: 20 40 10 30 

❮ Java.util - HashSet