Iterate over the elements of HashSet in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 10-Jan-2019 14:10:16
Advertisements