Convert HashSet to ArrayList

In this tutorial, You will learn, How to convert HashSet to ArrayList in Java. You have learned about the HashSet in Java earlier, Now you will see the concepts HashSet conversion to Array and ArrayList in brief.

 

Convert HashSet to Array

To convert HashSet to Array, we have inbuilt method toArray() in java.

Let’s see how can we convert the ArrayList into Array using toArray() method of ArrayList class.

Output:

HashSet contains: [Matt, Anshul, John, Eden, Mirilla]
Array elements: 
Matt
Anshul
John
Eden
Mirilla

 

In the above function, First we have created the HasSet named hset then added some values in HashSet. Then we declared an Array and copied the HashSet elements into the Array using toArray() method.

 

Convert HashSet to ArrayList

We can convert the HashSet into the ArrayList. Here first we create the HashSet then we will create the ArrayList and then copied the HashSet into the ArrayList. Let’s see how can we do that –

Output:

HashSet contains: [Matt, Anshul, John, Eden, Mirilla]
ArrayList contains: [Matt, Anshul, John, Eden, Mirilla]

 

In the above example, First we have declared the HashSet, and then add some elements in the HashSet.

After that, we declared ArrayList and pass HashSet object to ArrayList constructor as a parameter to copy the HashSet values into the ArrayList and the print the ArrayList.

This is, How can we convert the HashSet to Array or ArrayList in Java.

 

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply