Create HashSet in Java - How to add Elements to HashSet

Last updated Apr 04, 2022

To create a HashSet, you first need to import the Java.util.HashSet package.  After importing this package, you can now create the Java HashSet using the following  syntax:

HashSet HashSet = new HashSet<>();


The HashSet Methods 

We operate on a HashSet using the following methods:

  • add()-  adds the specified  set elements

  • addAll()- adds  all the elements  of the specified  set collection

  • iterator()- enables accessing of the Set elements

  • remove()- The specified elements are removed from the HashSet

  • removeAll()- Removes all elements from the set

  • addAll()- Performs union between two sets.


How to Add Elements to HashSet

import java.util.HashSet;

public class HashSetExamples {

    public static void main(String[] args) {

          HashSet HS = new HashSet<>();

            // Using add() method




            System.out.println("First HashSet: " + HS);

            HashSet HS2 = new HashSet<>();

            // Using addAll() method



            System.out.println("Second HashSet: " + HS2);





First HashSet : [8, 9, 10]

Second HashSet : [8, 9, 10, 11]

Article Contributed By :


Subscribe For Daily Updates

Flutter Questions
Android Questions