Convert HashSet to TreeSet in Java

In the last tutorial we have seen how to convert HashSet to an Array in java.I have already shared the difference between TreeSet and HashSet in java. In this tutorial we will see how to convert HashSet to TreeSet in java. We have a HashSet of Strings and we are converting into TreeSet of strings by copying all the elements of HashSet to TreeSet.


Program to Convert HashSet to TreeSet in Java 



import java.util.*;

 public class HashSettoTreeSet {
    public static void main(String args[]) {
        
    // Declaring a HashSet
    HashSet<String> hashset = new HashSet<String>();
    // Add elements to HashSet
    hashset.add("Pear");
    hashset.add("Apple");
    hashset.add("Orange");
    hashset.add("Papaya");
    hashset.add("Banana");
    //Showing HashSet elements
    System.out.println("HashSet contains :" + hashset);
    // Creating a TreeSet of HashSet elements
    TreeSet<String> treeset = new TreeSet<String>(hashset);
    
    //Showing TreeSet elements
    System.out.println("TreeSet contains :");
    for(String str : treeset){
        System.out.println(str);
    }
  }
 }  


Output
HashSet contains :[Apple, Pear, Papaya, Orange, Banana]
TreeSet contains :
Apple
Banana
Orange
Papaya
Pear



About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry