VOOZH about

URL: https://www.geeksforgeeks.org/java/merge-two-treesets-into-one-while-preserving-natural-order/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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:


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.
Comment