Open In App

How to Merge Two TreeSets into One while Preserving Natural Order?

In Java, TreeSet is a pre-defined class that implements the Set interface, and it provides a sorted set of elements with no duplicates. This uses a Red-Black Tree data structure for storage. It is a part of the java.util package.

Key Terminologies:



Syntax of Creating a TreeSet:

TreeSet<Type> treeSet = new TreeSet<>();

Step-by-Step Implementation:

Below is the Program to Merge Two TreeSets into One while Preserving Natural Order:




// Java program to merge two TreeSets
// Into one while preserving natural order
import java.util.TreeSet;
  
// Driver Class
public class GfGMergeTreeSets 
{
      // Main Function
    public static void main(String args[]) 
    {
        // Create two TreeSets
        TreeSet<Integer> set1 = new TreeSet<>();
             
          // Adding the elements into the set1
        set1.add(5);
        set1.add(25);
        set1.add(15);
  
        TreeSet<Integer> set2 = new TreeSet<>();
          
          // Adding the elements into the set1
        set2.add(3);
        set2.add(8);
        set2.add(12);
  
        // Merge the two TreeSets
        TreeSet<Integer> mergedSet = new TreeSet<>(set1);
        mergedSet.addAll(set2);
  
        System.out.println("Merged TreeSet: " + mergedSet);
    }
}

Output

Merged TreeSet: [3, 5, 8, 12, 15, 25]

Explanation of the above Program:


Article Tags :