HashSet implements the Set interface and inherits the AbstratSet class in Java that uses a HashTable for storage. HashSet applies the random order of the elements. Here, In this post, we will see an example on how to create a HashSet in java and how to iterates its data.

Simplest Presentation of Java HashSet Share on X

Points to remember:

  1. HashSet elements would get returned in any random order.
  2. Java HashSet won’t return duplicate elements as If there is a duplicate element in the HashSet then the old value would be overwritten.
  3. Java HashSet is non-synchronized.
  4. HashSet allows null values.

Syntax:

HashSet<Integer> hashSet = new HashSet<>();

 

Note: In below example 1, we are creating HashSet of type Integer and in example 2, it’s of String.

Example 1

import java.util.HashSet;

public class HashSetIntegerSample {
 
 public static void main(String[] args) {
  
  HashSet < Integer > hashSetInteger = new HashSet < > ();
  hashSetInteger.add(107);
  hashSetInteger.add(90);
  hashSetInteger.add(35);
  hashSetInteger.add(95);
  hashSetInteger.add(5);
  hashSetInteger.add(90);
  
  for (int hsi: hashSetInteger) {
   System.out.println(hsi);
  }
 }
}

 

Output 1:

35 
5 
90 
107 
95

 

Note: it could come to a different order for everyone.

 

Example 2

import java.util.HashSet;

public class HashSetStringSample {
 
 public static void main(String[] args) {
  
  HashSet < String > hashSetString = new HashSet < > ();
  hashSetString.add("Yogi");
  hashSetString.add("Gaurangee");
  hashSetString.add("Pulkit");
  hashSetString.add("Isha");
  hashSetString.add("Yash");
  hashSetString.add("Yash");
  hashSetString.add("Deepak");
  
  for (String hss: hashSetString) {
   System.out.println(hss);
  }
 }
}

 

Output 2:

Isha 
Yogi 
Yash 
Pulkit 
Gaurangee 
Deepak

 

 

If you like this post, please check out my other similar posts:

HashTable in Java with Example

 

Reference:

     Hashtable Javadoc

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts