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

  1. import java.util.*;
  2.  
  3. public class HashSetEnhancedForLoop {
  4.     public static void main(String[] args) {
  5.     HashSet<Integer> hs= new HashSet<Integer>();
  6.       hs.add(14);
  7.       hs.add(7);
  8.       hs.add(21);
  9.       hs.add(28);
  10.       System.out.println("Enhanced For Loop");
  11.       for (Integer element : hs) {            
  12.            System.out.println(element);        
  13.       }
  14.     }
  15. }
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

  1. import java.util.*;
  2.  
  3. public class HashSetIterator {
  4.     public static void main(String[] args) {
  5.     HashSet<Integer> hs= new HashSet<Integer>();
  6.       hs.add(14);
  7.       hs.add(7);
  8.       hs.add(21);
  9.       hs.add(28);
  10.       System.out.println("While with iterator");
  11.       Iterator itr = hs.iterator();
  12.       while (itr.hasNext()) {
  13.          System.out.println(itr.next());
  14.       }
  15.     }
  16. }
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

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on