Note that HashSet elements are not ordered, so the traversed elements can be printed in any order.
-
Using an Iterator : The iterator() method is used to get an iterator over the elements in this set. The elements are returned in no particular order. Below is the java program to demonstrate it.
// Java program to demonstrate iteration over// HashSet using an iteratorimportjava.util.*;classIterationDemo {publicstaticvoidmain(String[] args){HashSet<String> h =newHashSet<String>();// Adding elements into HashSet usind add()h.add("Geeks");h.add("for");h.add("Geeks");// Iterating over hash set itemsIterator<String> i = h.iterator();while(i.hasNext())System.out.println(i.next());}}chevron_rightfilter_noneOutput:Geeks for
- Using for-each loop :
// Java program to demonstrate iteration over// HashSet using an Enhanced for-loopimportjava.util.*;classIterationDemo {publicstaticvoidmain(String[] args){// your code goes hereHashSet<String> h =newHashSet<String>();// Adding elements into HashSet usind add()h.add("Geeks");h.add("for");h.add("Geeks");// Iterating over hash set itemsfor(String i : h)System.out.println(i);}}chevron_rightfilter_noneOutput:Geeks for
-
Using forEach() method :
In Java 8 or above, we can iterate a List or Collection using forEach() method.// Java program to demonstrate iteration over// HashSet using forEach() methodimportjava.util.*;classIterationDemo {publicstaticvoidmain(String[] args){// your code goes hereHashSet<String> h =newHashSet<String>();// Adding elements into HashSet usind add()h.add("Geeks");h.add("for");h.add("Geeks");// Iterating over hash set itemsh.forEach(i -> System.out.println(i));}}chevron_rightfilter_noneOutput:Geeks for
Recommended Posts:
- Traverse through a HashMap in Java
- HashSet in Java
- HashSet vs TreeSet in Java
- HashSet contains() Method in Java
- Initializing HashSet in Java
- How to sort HashSet in Java
- HashSet add() Method in Java
- HashSet isEmpty() Method in Java
- HashSet clone() Method in Java
- HashSet size() Method in Java
- HashSet remove() Method in Java
- HashSet iterator() Method in Java
- Internal working of Set/HashSet in Java
- HashSet clear() Method in Java
- HashSet removeAll() method in Java with Example
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



