In this post we will see how to iterate HashSet in java. We can iterate HashSet either using
1. For loop
2. Iterator.
We will see examples for all these methods.
1. Iterate HashSet in Java using For Loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.kscodes.sampleproject; import java.util.HashSet; import java.util.Set; public class IterateHashSetExample1 { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(); hashSet.add("Java"); hashSet.add("JSP"); hashSet.add("JavaScript"); hashSet.add("JQuery"); System.out.println("Iterating HashSet using For each Loop"); for (String ele : hashSet) { System.out.println(ele); } } } |
Ouput
1 2 3 4 5 |
Iterating HashSet using For each Loop JSP JQuery JavaScript Java |
2. Iterate HashSet in Java using Iterator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.kscodes.sampleproject; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class IterateHashSetExample { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(); hashSet.add("Java"); hashSet.add("JSP"); hashSet.add("JavaScript"); hashSet.add("JQuery"); System.out.println("Iterating HashSet using Iterator"); Iterator<String> iterator = hashSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } } |
Ouput
1 2 3 4 5 |
Iterating HashSet using Iterator JSP JQuery JavaScript Java |
Please Note
You will notice that the Elements from hashSet when printed are not in the Order in which we added them.
HashSet doesn’t preserve the order of the elements in which they are inserted.