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.



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

Example 1


Output 1:


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


Example 2


Output 2:



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

HashTable in Java with Example



     Hashtable Javadoc


  • 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.

    http://Techndeck.com deepak.rkgit@gmail.com Verma Deepak