HashSet iterator() method in java

Let’s learn HashSet iterator() method in java.

HashSet iterator() method in java

iterator() method of HashSet class returns an iterator over the elements in this set. The elements are returned in no particular order.

Syntax:

public Iterator<E> iterator()

Parameters:

iterator() method does not take any parameter.

Returns:

an Iterator over the elements in this set.

Also read – HashSet in java

Now let’s see example on HashSet iterator() method.

import java.util.HashSet;
import java.util.Iterator;
public class HashSetIteratorMethodExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Welcome");
      hs.add("hello");
      hs.add("world");
      hs.add("core");
      hs.add("java");
      System.out.println("HashSet values are: " + hs);
      // create an Iterator
      Iterator<String> value = hs.iterator();
      System.out.println("iterator values are: ");
      while(value.hasNext())
      {
         System.out.println(value.next());
      }
   }
}


Output:

HashSet values are: [core, world, java, Welcome, hello]
iterator values are:
core
world
java
Welcome
hello

1 Comment

Comments are closed.