1. Using HashSet constructor [Easiest]
2. Using for-each
3. Using addAll() method
Read Also : 3 ways to Convert HashSet to TreeSet in Java
Let's dive deep into the topic of converting TreeSet to HashSet in Java.
Convert TreeSet to HashSet in Java
1. Using HashSet constructor
The easiest way to convert TreeSet to HashSet in Java is by using HashSet constructor as shown below in the example:
import java.util.*;
public class TreeSetToHashSet {
public static void main(String args[]) {
// Create a TreeSet object
TreeSet<String> treeset = new TreeSet<String>();
// Adding elements to TreeSet object
treeset.add("India");
treeset.add("USA");
treeset.add("Canada");
// Displaying TreeSet elements
System.out.println("Printing TreeSet elements: "+ treeset);
// Converting TreeSet to HashSet using Constructor
HashSet<String> hashset = new HashSet<>(treeset);
// Printing HashSet elements
System.out.println("Printing HashSet elements: "+ hashset);
}
}
Output:
Printing TreeSet elements: [Canada, India, USA]
Printing HashSet elements: [Canada, USA, India]
2. Using for-each
Another way to convert TreeSet to HashSet in Java is by using for-each as shown below in the example:
import java.util.*;
public class TreeSetToHashSet2 {
public static void main(String args[]) {
// Creating a TreeSet object
TreeSet<String> treeset2 = new TreeSet<String>();
// Add elements to TreeSet object
treeset2.add("Element1");
treeset2.add("Element2");
treeset2.add("Element3");
// Printing TreeSet elements
System.out.println("Displaying TreeSet elements: "+ treeset2);
// Creating HashSet Object
HashSet<String> hashset2 = new HashSet<>();
// Converting TreeSet to HashSet using for-each
for(String str : treeset2)
{
hashset2.add(str);
}
// Displaying HashSet elements
System.out.println("Displaying HashSet elements: "+ hashset2);
}
}
Output:
Displaying TreeSet elements: [Element1, Element2, Element3]
Displaying HashSet elements: [Element3, Element2, Element1]
3. Using addAll() method
We can also use addAll() method to convert TreeSet to HashSet in Java as shown below in the example:
import java.util.*;
public class TreeSetToHashSet3 {
public static void main(String args[]) {
// Instantiating a TreeSet object
TreeSet<String> treeset3 = new TreeSet<String>();
// Putting elements to TreeSet object
treeset3.add("Alive");
treeset3.add("is");
treeset3.add("Awesome");
// Showing TreeSet elements
System.out.println("Showing TreeSet elements: "+ treeset3);
// Instantiating HashSet Object
HashSet<String> hashset3 = new HashSet<>();
// Converting TreeSet to HashSet using addAll() method
hashset3.addAll(treeset3);
// Showing HashSet elements
System.out.println("Showing HashSet elements: "+ hashset3);
}
}
Output:
Showing TreeSet elements: [Alive, Awesome, is]
Showing HashSet elements: [Awesome, is, Alive]
That's all for today. Please mention in the comments if you have any questions related to how to convert TreeSet to HashSet in Java.
0 Commentaires