Write a Java program to convert a hash set to a tree set


In the program, a HashSet named hash_set is created and populated with some elements: "Black", "White", "Pink", "Red", "Green", and "Yellow". The program then creates a TreeSet named tree_set by passing hash_set as an argument to the TreeSet constructor. This constructor automatically sorts the elements in the TreeSet in ascending order. Finally, the contents of the HashSet and TreeSet are printed to the console.

Source Code

import java.util.*;
public class HashSet_TreeSet
{
	public static void main(String[] args)
	{
		HashSet<String> hash_set = new HashSet<String>();
		hash_set.add("Black");
		hash_set.add("White");
		hash_set.add("Pink");
		hash_set.add("Red");
		hash_set.add("Green");
		hash_set.add("Yellow");
		System.out.println("Hash Set : " + hash_set);
 
		// Creat a TreeSet of HashSet elements
		Set<String> tree_set = new TreeSet<String>(hash_set);
 
		// Display TreeSet elements
		System.out.println("TreeSet : "+tree_set);
	}
}

Output

Hash Set : [Red, White, Pink, Yellow, Black, Green]
TreeSet : [Black, Green, Pink, Red, White, Yellow]

Example Programs