In this Article we will discuss how to initialize a HashSet using a Array or a Collection.

HashSet has a Constructor that receives a Collection as an argument and initializes the new Set with the elements of passed collection object.

Initializing a HashSet with an array

Suppose we need to initialize our String HashSet with following array i.e.

But array is not a Collection, hence we need to first convert this into a List i.e.

Now we can use this List to initialize our HashSet. Check the following example to  initialize HashSet with String array i.e.


How to initialize a HashSet with an another HashSet

It can be done using the same HashSet constructor that receives another collection as an argument and adds all its element to the HashSet.

Checkout following example,



Click Here to Subscribe for more Articles / Tutorials like this.