1. Using TreeSet constructor [Easiest]
2. Using addAll() method
3. Using for-each
Read Also: Difference between HashSet and TreeSet in Java
Let's dive deep into the topic:
Convert HashSet to TreeSet in Java
1. Using TreeSet constructor
The easiest way to convert HashSet to TreeSet is by using TreeSet constructor as shown below in the example:
import java.util.*;
public class HashSetToTreeSet {
public static void main(String args[]) {
// Creating a HashSet object
HashSet<String> hashset = new HashSet<String>();
// Putting elements to HashSet object
hashset.add("Air");
hashset.add("Water");
hashset.add("Fire");
// Printing HashSet elements
System.out.println("HashSet elements are: "+ hashset);
// Converting HashSet to TreeSet using TreeSet constructor
TreeSet<String> treeset = new TreeSet<>(hashset);
// Iterating over the TreeSet elements
for (String element : treeset)
{
System.out.println("TreeSet elements are: "+ element);
}
}
}
Output:
HashSet elements are: [Water, Fire, Air]
TreeSet elements are: Air
TreeSet elements are: Fire
TreeSet elements are: Water
2. Using addAll() method
Another way to convert HashSet to TreeSet in Java is by using addAll() method as shown below in the example:
import java.util.*;
public class HashSetToTreeSet2 {
public static void main(String args[]) {
// Create a HashSet object
HashSet<String> hashset2 = new HashSet<String>();
// Adding elements to HashSet object
hashset2.add("Books");
hashset2.add("Bag");
hashset2.add("Bottle");
// Displaying HashSet elements
System.out.println("Printing HashSet elements: "+ hashset2);
// Creating TreeSet object
TreeSet<String> treeset2 = new TreeSet<>();
// Converting HashSet to TreeSet using addAll() method
treeset2.addAll(hashset2);
// Iterating and printing the TreeSet elements
for (String str : treeset2)
{
System.out.println("TreeSet element is: "+ str);
}
}
}
Output:
Printing HashSet elements: [Bottle, Bag, Books]
TreeSet element is: Bag
TreeSet element is: Books
TreeSet element is: Bottle
3. Using for-each
We can also convert HashSet to TreeSet using for-each loop as shown below in the example:
import java.util.*;
public class HashSetToTreeSet3 {
public static void main(String args[]) {
// Initializing HashSet object
HashSet<String> hashset3 = new HashSet<String>();
// Put elements to HashSet object
hashset3.add("Washing Machine");
hashset3.add("Television");
hashset3.add("Refrigerator");
// Showing HashSet elements
System.out.println("Showing HashSet elements: "+ hashset3);
// Producing TreeSet object
TreeSet<String> treeset3 = new TreeSet<>();
// Converting HashSet to TreeSet using for-each
for (String str : hashset3)
{
treeset3.add(str);
}
System.out.println("TreeSet elements are: "+ treeset3);
}
}
Output:
Showing HashSet elements: [Television, Refrigerator, Washing Machine]
TreeSet elements are: [Refrigerator, Television, Washing Machine]
That's all for today. Please mention in the comments if you have any questions related to how to convert HashSet to TreeSet in Java.