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:
- Set: A set can be defined as a collection that contains unique elements. The Set interface can be implemented in the TreeSet class.
- Comparator: The comparator is a pre-defined interface, and it is used to define the custom ordering for objects it can be provided custom ordering with specified rules by the comparator.
Syntax of Creating a TreeSet:
TreeSet<Type> treeSet = new TreeSet<>();Step-by-Step Implementation:
- Create the class named GfGMergeTreeSets and write the main method into the class.
- Now, create the two tree sets and add the elements into the tree sets.
- Create one more TreeSet with one TreeSet element, then add another tree element into it.
- Print the resultant tree set.
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:
- The above Java program is the example of merging two tree sets into one while preserving natural order.
- We have created two tree sets and added the elements to the two tree sets.
- After that, we have created one more tree set with the set1 element and added the set2 using the addAll() method.
- A last, all elements are merged and stored in the sorted order of the tree set.