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

            HS.add(8);

            HS.add(9);

            HS.add(10);

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

            HashSet HS2 = new HashSet<>();

            // Using addAll() method

            HS2.addAll(HS);

            HS2.add(11);

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

    }

}

 

Output:

First HashSet : [8, 9, 10]

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

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

167 Views