Hashset with looping
In this article, we will see how to loop Hashset in java
Its very much common requirement to iterate or loop through Hashset in java applications
There are mainly 2 ways to loop through Hashset in java
1) Enhanced For loop
2) Iterator
Let’s see each of these ways with an example
1) Enhanced For loop
- import java.util.*;
- public class HashSetEnhancedForLoop {
- public static void main(String[] args) {
- HashSet<Integer> hs= new HashSet<Integer>();
- hs.add(14);
- hs.add(7);
- hs.add(21);
- hs.add(28);
- System.out.println("Enhanced For Loop");
- for (Integer element : hs) {
- System.out.println(element);
- }
- }
- }
import java.util.*; public class HashSetEnhancedForLoop { public static void main(String[] args) { HashSet<Integer> hs= new HashSet<Integer>(); hs.add(14); hs.add(7); hs.add(21); hs.add(28); System.out.println("Enhanced For Loop"); for (Integer element : hs) { System.out.println(element); } } }
Note : In the above example, we have used advanced/enhanced for loop to iterate HashSet
2) Iterator
- import java.util.*;
- public class HashSetIterator {
- public static void main(String[] args) {
- HashSet<Integer> hs= new HashSet<Integer>();
- hs.add(14);
- hs.add(7);
- hs.add(21);
- hs.add(28);
- System.out.println("While with iterator");
- Iterator itr = hs.iterator();
- while (itr.hasNext()) {
- System.out.println(itr.next());
- }
- }
- }
import java.util.*; public class HashSetIterator { public static void main(String[] args) { HashSet<Integer> hs= new HashSet<Integer>(); hs.add(14); hs.add(7); hs.add(21); hs.add(28); System.out.println("While with iterator"); Iterator itr = hs.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } } }
Note : We can’t access HashSet elements using index in the way we access in Arraylist