Iterate through elements of HashSet in Java


Create a HashSet and add elements to it −

Set<Integer> hs = new HashSet<Integer>();
hs.add(20);
hs.add(39);
hs.add(67);
hs.add(79);
hs.add(81);
hs.add(87);

Try the below given code to iterate through the elements −

Iterator i = hs.iterator();
while (i.hasNext())
System.out.println(i.next());

To iterate through the elements of HashSet, try the following code −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      Set<Integer> hs = new HashSet<Integer>();
      hs.add(20);
      hs.add(39);
      hs.add(67);
      hs.add(79);
      hs.add(81);
      hs.add(87);
      hs.add(88);
      System.out.println("Elements = "+hs);
      Iterator i = hs.iterator();
      while (i.hasNext())
      System.out.println(i.next());
   }
}

Output

Elements = [81, 67, 20, 39, 87, 88, 79]
81
67
20
39
87
88
79

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements