Convert HashSet to TreeSet

Price: INR 8,999.00
Price: INR 14,999.00
Was: INR 16,999.00

In last tutorials you have seen, How can we implement the TreeSet and you have seen the different methods of the HashSet. Now you will see how to convert HashSet to TreeSet.

In this tutorial, we will see the conversion of HashSet into TreeSet.

In this example, we have declared an HashSet named ‘hSet’ and a TreeSet named ‘tSet’.We have added the elements in the HashSet and then print the HashSet value.


Convert HashSet to TreeSet

At the time of TreeSet declaration, We have copied the HashSet into the TreeSet. Let’s see the actual implementation-


HashSet contains: [100, 101, 8, 25, 75]
TreeSet Contains: [8, 25, 75, 100, 101]


As you can see in the output, We have successfully converted the HashSet into TreeSet because values in the TreeSet are sorted.


How to convert Array into TreeSet

Let’s see how can we convert the Array into TreeSet. We can convert the Array into any Set like this. Let’s see the code implementation-


TreeSet contains : [4, 5, 6, 7, 8, 9, 10]


In the above example, We have seen how can we converted the Array into Set.

First, we have converted the Array into List using Arrays.AsList() method then we converted that List to Set easily.

Have you noticed? TreeSet elements are different from actual Array elements.


Elements in the TreeSet are unique and sorted(as per Set properties). So using this way you can remove the duplicate Elements from the Array.

So this implementation actually answers of three problems-

  • How to convert Array into Set or TreeSet

  • How can we remove the duplicate values from Array

  • How can we sort the Array and Remove the Duplicate Values


You can try another conversion by yourself. It will help you to make your concepts clear and used to write collection code.


Selenium Tutorial:

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

0 Comment

Leave a Reply