How to convert a HashSet to a TreeSet
To convert a HashSet to a TreeSet, simply create a TreeSet with a HashSet as a parameter. This is possible because HashSet is a collection of data. You can also create an empty TreeSet, then copy all the elements with the method addAll(Collection c).
Example:
We have a HashSet of String and we want to create a TreeSet of String by copying the elements of HashSet into TreeSet:
Example:
We have a HashSet of String and we want to create a TreeSet of String by copying the elements of HashSet into TreeSet:
import java.util.HashSet;Output:
import java.util.TreeSet;
import java.util.Set;
public class HashSettoTreeSet{
public static void main(String[] args) {
HashSethashset = new HashSet ();
hashset.add("E1");
hashset.add("E2");
hashset.add("E3");
hashset.add("E4");
hashset.add("E5");
System.out.println("HashSet: "+ hashset);
// create a TreeSet with the elements of HashSet
Settreeset = new TreeSet (hashset);
System.out.println("TreeSet: ");
for(String e : treeset){
System.out.println(e);
}
}
}
HashSet: [E1, E2, E3, E4, E5]
TreeSet: [E1, E2, E3, E4, E5]