Description
Program to convert a HashSet to a TreeSet
Program
Here is the complete code for HashSet to TreeSet conversion. We have a HashSet of Strings and we are creating a TreeSet of strings by copying all the elements of HashSet to TreeSet.
import java.util.HashSet; import java.util.TreeSet; import java.util.Set; class ConvertHashSettoTreeSet{ public static void main(String[] args) { // Create a HashSet HashSet<String> hset = new HashSet<String>(); //add elements to HashSet hset.add("Element1"); hset.add("Element2"); hset.add("Element3"); hset.add("Element4"); // Displaying HashSet elements System.out.println("HashSet contains: "+ hset); // Creating a TreeSet of HashSet elements Set<String> tset = new TreeSet<String>(hset); // Displaying TreeSet elements System.out.println("TreeSet contains: "); for(String temp : tset){ System.out.println(temp); } } }
Output:
HashSet contains: [Element1, Element2, Element3, Element4] TreeSet contains: Element1 Element2 Element3 Element4
Rohit Chakrapani says
This example is fine… but if you would have given some unsorted input to HashSet and then converted it into TreeSet,then it would have being more beneficial for the beginners as it will also clear the concept of indirect sorting using HashSet.
Rohit Chakrapani says
You have done a great job !!! Many are benefited from this site. Thanks a lot.
Bhanu ravali says
It’s beneficial but in the topic convert HashSet to TreeSet, I did not get to covert HashSet to TreeSet ,created a variable to Set interface and then address of treeSet object stored in that variable.why not we did not create a variable for treeSet.if you give some more explanation, it’s beneficial for beginners.
Set s= new TreeSet(hSet);
Why not like below
TreeSet t=new TreeSet(hset);
Sud says
Because HashSet gives better performance (faster) than TreeSet for the operations like add, remove, contains, size etc. HashSet offers constant time cost while TreeSet offers log(n) time cost for such operations.
Nagababu says
in above program (string temp) for what purpose we use this
venkatesh says
That is for temporary reference variable to display map values