Convert HashSet to TreeSet in Java



In this article, we will learn to convert a HashSet to a TreeSet in Java. Converting from one type of collection to another is a simple process when we require them to change their behavior or the nature of our data structure.

Why Convert HashSet to TreeSet?

For the following operations, we can convert a HashSet to a TreeSet ?

Using the TreeSet Constructor

The easiest way to do the conversion of such a HashSet is by providing the same HashSet as an argument to the TreeSet constructor.

The following are the steps to convert a HashSet to a TreeSet in Java ?

  • Create a HashSet and add some names to it.
  • Print the HashSet: The output will be unordered since HashSet does not maintain any specific order.
  • Convert the HashSet to a TreeSet by passing the HashSet to the TreeSet constructor; this sorts the elements.
  • Print the TreeSet: The names will now appear in their natural, sorted order (alphabetical for strings

At first, create a HashSet with string values using the add() method ?

HashSet<String> hashSet = new HashSet<String>();
hashSet.add("Bradley");
hashSet.add("Katie");
hashSet.add("Brad");
hashSet.add("Amy");
hashSet.add("Ryan");
hashSet.add("Jamie");

Now, convert the HashSet to TreeSet ?

Set<String> set = new TreeSet<String>(hashSet);

Example

Below is an example to convert a HashSet to a TreeSet in Java ?

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class Demo {
   public static void main(String[] args) {
      HashSet<String> hashSet = new HashSet<String>();
      hashSet.add("Bradley");
      hashSet.add("Katie");
      hashSet.add("Brad");
      hashSet.add("Amy");
      hashSet.add("Ryan");
      hashSet.add("Jamie");
      hashSet.add("Kevin");
      hashSet.add("David");
      System.out.println("HashSet = "+ hashSet);
      Set<String> set = new TreeSet<String>(hashSet);
      System.out.println("TreeSet = "+set);
   }
}

Output

HashSet = [Kevin, Jamie, Ryan, Bradley, Katie, David, Brad, Amy]
TreeSet = [Amy, Brad, Bradley, David, Jamie, Katie, Kevin, Ryan]

Time complexity: O(N log N), due to inserting N elements into a balanced tree.
Space complexity: O(N), as a new TreeSet is created to store the elements.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-03-29T02:56:23+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements