How to Merge Two TreeSets into One while Preserving Natural Order?
Last Updated :
21 Feb, 2024
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
import java.util.TreeSet;
public class GfGMergeTreeSets
{
public static void main(String args[])
{
TreeSet<Integer> set1 = new TreeSet<>();
set1.add( 5 );
set1.add( 25 );
set1.add( 15 );
TreeSet<Integer> set2 = new TreeSet<>();
set2.add( 3 );
set2.add( 8 );
set2.add( 12 );
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.
Share your thoughts in the comments
Please Login to comment...