Open In App

Convert HashSet to TreeSet in Java

Last Updated : 03 Jan, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Hashset: Hashset in Java is generally used for operations like search, insert and delete. It takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table.

TreeSet: TreeSet in Java takes O(log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data. Also, it supports operations like higher() (Returns least higher element), floor(), ceiling(), etc. These operations are also O(log n) in TreeSet and not supported in HashSet. TreeSet is implemented using a Self Balancing Binary Search Tree (Red-Black Tree). TreeSet is backed by TreeMap in Java.

In general, if you want a sorted set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it.

Given a HashSet the task is to convert it into TreeSet in Java.

Examples:

HashSet: [Geeks, For, Welcome, To]
TreeSet: [For, Geeks, To, Welcome]

HashSet: [1, 2, 3, 4, 5]
TreeSet: [1, 2, 3, 4, 5]

We can convert HashSet to TreeSet in following ways:

  • By invoking the parameterized constructor and sending object of Hash set as a parameter to it.
    1. First, we have to create an object for the hash set.
    2. Then we have to add all the elements to the hash set.
    3. Finally, create an object for the tree set and send the hash set object to it.

    Below is the implementation of the above approach:

    Program:




    import java.util.HashSet;
    import java.util.Set;
    import java.util.TreeSet;
      
    public class GFG {
      
        public static void main(String[] args)
        {
      
            // Get the HashSet
            Set<String> setobj = new HashSet<>();
            setobj.add("Welcome");
            setobj.add("To");
            setobj.add("Geeks");
            setobj.add("For");
            setobj.add("Geeks");
      
            System.out.println("HashSet: "
                               + setobj);
      
            // Convert the HashSet to TreeSet
            Set<String> hashSetToTreeSet
                = new TreeSet<>(setobj);
      
            // Print the TreeSet
            System.out.println("TreeSet: "
                               + hashSetToTreeSet);
        }
    }

    
    

    Output:

    HashSet: [Geeks, For, Welcome, To]
    TreeSet: [For, Geeks, To, Welcome]
    
  • By constructing a tree set containing the same elements present in the hash set by using addAll method.
    1. First, we have to create an object for the hash set.
    2. Then we have to add all the elements to the hash set.
    3. Now create an object for the treeset .
    4. Using addAll method add all elements of hash set to it.

    Below is the implementation of the above approach:

    Program:




    import java.util.HashSet;
    import java.util.Set;
    import java.util.TreeSet;
      
    public class GFG {
      
        public static void main(String[] args)
        {
      
            // Get the HashSet
            Set<String> setobj = new HashSet<>();
            setobj.add("Welcome");
            setobj.add("To");
            setobj.add("Geeks");
            setobj.add("For");
            setobj.add("Geeks");
      
            System.out.println("HashSet: "
                               + setobj);
      
            // Convert the HashSet to TreeSet
            Set<String> hashSetToTreeSet
                = new TreeSet<>();
            hashSetToTreeSet.addAll(setobj);
      
            // Print the TreeSet
            System.out.println("TreeSet: "
                               + hashSetToTreeSet);
        }
    }

    
    

    Output:

    HashSet: [Geeks, For, Welcome, To]
    TreeSet: [For, Geeks, To, Welcome]
    
  • By using a for each loop.( This method is commonly used for conversion between two incompatible types.)
    1. First, we have to create an object for the hash set.
    2. Then we have to add all the elements to the hash set.
    3. Now create an object for the treeset .
    4. Finally, by using for each loop adding all elements of hash set to the tree set.

    Below is the implementation of the above approach:

    Program:




    import java.util.HashSet;
    import java.util.Set;
    import java.util.TreeSet;
      
    public class GFG {
      
        public static void main(String[] args)
        {
      
            // Get the HashSet
            Set<String> setobj = new HashSet<>();
            setobj.add("Welcome");
            setobj.add("To");
            setobj.add("Geeks");
            setobj.add("For");
            setobj.add("Geeks");
      
            System.out.println("HashSet: "
                               + setobj);
      
            // Convert the HashSet to TreeSet
            Set<String> hashSetToTreeSet
                = new TreeSet<>();
            for (String i : setobj)
                hashSetToTreeSet
                    .add(i);
      
            // Print the TreeSet
            System.out.println("TreeSet: "
                               + hashSetToTreeSet);
        }
    }

    
    

    Output:

    HashSet: [Geeks, For, Welcome, To]
    TreeSet: [For, Geeks, To, Welcome]
    


  • Previous Article
    Next Article

    Similar Reads

    How to Copy or Append HashSet to Another HashSet in Java?
    HashSet is used to store distinct values in Java. HashSet stores the elements in random order, so there is no guarantee of the elements' order. The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. We can copy or append a HashSet to another HashSet. There is a couple of ways to copy HashSet or
    4 min read
    HashSet vs TreeSet in Java
    When it comes to discussing differences between Set the firstmost thing that comes into play is the insertion order and how elements will be processed. HashSet in java is a class implementing the Set interface, backed by a hash table which is actually a HashMap instance. This class permits the null element. The class also offers constant time perfo
    5 min read
    Difference and similarities between HashSet, LinkedHashSet and TreeSet in Java
    In this article, we will learn, the difference between HashSet vs LinkedHashSet and TreeSet And similarities between LinkedHashSet and TreeSet. HashSet, LinkedHashSet, and TreeSet all implement the Set interface. So we have tried to list out the differences and similarities between HashSet, LinkedHashSet, and TreeSet in java. Differences Between Ha
    6 min read
    Convert HashSet to a ArrayList in Java
    ArrayList class is a resizable array, present in java.util package. The difference between an array and an ArrayList in Java, is that the size of an array cannot be modified (i.e. if you want to append/add or remove element(s) to/from an array, you have to create a new array. However, elements can be added/appended or removed from an ArrayList with
    4 min read
    Convert HashSet to array in Java
    Java HashSet class is used to create a collection that uses a hash table for the storage of elements. It inherits AbstractSet class and implements Set Interface. The key points about HashSet are: HashSet contains unique elements only.HashSet allows null values.The insertion of elements in a HashSet is based on a hashcode.HashSet is best used for se
    2 min read
    How to Convert Comma Separated String to HashSet in Java?
    Given a Set of String, the task is to convert the Set to a comma-separated String in Java. Examples: Input: Set&lt;String&gt; = ["Geeks", "ForGeeks", "GeeksForGeeks"] Output: "Geeks, For, Geeks" Input: Set&lt;String&gt; = ["G", "e", "e", "k", "s"] Output: "G, e, e, k, s" There are two ways in which we can convert comma separated string to Java Hash
    2 min read
    How to Convert ArrayList to HashSet in Java?
    ArrayList: In Java, ArrayList can have duplicates as well as maintains insertion order. HashSet: HashSet is the implementation class of Set. It does not allow duplicates and uses Hashtable internally. There are four ways to convert ArrayList to HashSet : Using constructor.Using add() method by iterating over each element and adding it into the Hash
    3 min read
    Convert Array to HashSet in Java
    The Single Data structure cannot be able to fulfill the requirements of the programmers that's why there are a lot of inbuilt Data-Structures in Programming languages. Arrays are the most commonly used Data-Structure in most programming languages. The advantage of this Data-Structure is O(1) accessing the elements of the Arrays with the help of ind
    3 min read
    Java Program to Convert List to HashSet
    The List interface provides a way to store the ordered collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. The HashSet class permits the null element. The class also offers constant time performance for the basic
    4 min read
    Convert a HashSet to a LinkedList in Java
    In Java, HashSet and LinkedList are linear data structures. These are majorly used in many cases. There may be some cases where we need to convert HashSet to LinkedList. So, in this article, we will see how to convert HashSet to LinkedList in Java. Java Program to Convert a HashSet to a LinkedList This is one of the simplest ways to convert HashSet
    2 min read