Iterate over the elements of HashSet in Java


Declare a HashSet and add elements −

Set hs = new HashSet();
hs.add(20);
hs.add(39);
hs.add(67);
hs.add(79);

Now, iterate over the elements −

for (Iterator i = hs.iterator(); i.hasNext();) {
   Object ele = i.next();
   System.out.println(ele);
}

The following is an example that iterate over the elements of HashSet −

Example

 Live Demo

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Set hs = new HashSet();
      hs.add(20);
      hs.add(39);
      hs.add(67);
      hs.add(79);
      System.out.println("Elements = ");
      for (Iterator i = hs.iterator(); i.hasNext();) {
         Object ele = i.next();
         System.out.println(ele);
       }
   }
}

Output

Elements =
67
20
39
79

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements