1. Introduction
In Java, converting a HashSet to a TreeSet can be useful when you have a set of elements that you want to sort in a natural order or by a custom comparator. The HashSet class stores elements in a hash table, which means it does not guarantee any specific order of its elements. In contrast, a TreeSet stores its elements in a red-black tree, providing an ordered set.
2. Program Steps
1. Create a HashSet object and add some elements to it.
2. Print the original HashSet.
3. Create a TreeSet object and use the parameterized constructor to initialize it with the HashSet.
4. Print the TreeSet.
3. Code Program
import java.util.HashSet;
import java.util.TreeSet;
public class ConvertHashSetToTreeSet {
public static void main(String[] args) {
// Step 1: Create a HashSet object and add some elements to it
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Banana");
hashSet.add("Apple");
hashSet.add("Cherry");
// Print the original HashSet
System.out.println("Original HashSet: " + hashSet);
// Step 3: Create a TreeSet object and use the parameterized constructor to initialize it with the HashSet
TreeSet<String> treeSet = new TreeSet<>(hashSet);
// Step 4: Print the TreeSet
System.out.println("TreeSet from HashSet: " + treeSet);
}
}
Output:
Original HashSet: [Banana, Cherry, Apple] TreeSet from HashSet: [Apple, Banana, Cherry]
4. Step By Step Explanation
Step 1: A HashSet named hashSet is created, and three elements – "Banana", "Apple", and "Cherry" are added to it. The order of these elements is not guaranteed to be in any specific order.
Step 3: A TreeSet named treeSet is created. The TreeSet class has a constructor that takes a Collection object, so we pass the hashSet to this constructor. This results in the TreeSet being initialized with the elements of the HashSet, sorted in their natural order.
Step 4: The TreeSet is printed, showing the elements in ascending order – "Apple", "Banana", "Cherry", demonstrating that the HashSet has been successfully converted to a TreeSet and the elements are ordered.