Java Collection Tutorial - Java HashSet.iterator()








Syntax

HashSet.iterator() has the following syntax.

public Iterator <E> iterator()

Example

In the following code shows how to use HashSet.iterator() method.

/*ww  w.  ja  va 2s  .  c  o  m*/

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

public class Main {
   public static void main(String args[]) {
      HashSet<String>  newset = new HashSet <String> ();
                  
      // populate hash set
      newset.add("Learning"); 
      newset.add("from");
      newset.add("java2s.com");   
      
      // create an iterator
      Iterator iterator = newset.iterator(); 
      
      // check values
      while (iterator.hasNext()){
         System.out.println("Value: "+iterator.next() + " ");  
      }
   }    
}

The code above generates the following result.