java.util.HashSet.iterator() Method


Advertisements


Description

The iterator() method is used to get an iterator over the elements in this set. The elements are returned in no particular order.

Declaration

Following is the declaration for java.util.HashSet.iterator() method.

public Iterator<E> iterator()

Parameters

  • NA

Return Value

The method call returns an Iterator over the elements in this set.

Exception

  • NA

Example

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

package com.tutorialspoint;

import java.util.*;

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

Let us compile and run the above program, this will produce the following result.

Value: Learning 
Value: Simply 
Value: Easy

java_util_hashset.htm

Advertisements