A TreeSet is a sorted set implementation of the Set interface based on a TreeMap. It uses a Red-Black tree to store elements. Elements are sorted according to their natural ordering, or a custom Comparator provided at the time of TreeSet creation.
- It does not allow duplicate elements or null values.
- It provides log(n) time complexity for basic operations like add, remove, and contains due to its tree implementation.
- Common methods include add(), remove(), contains(), first(), last(), lower(), higher() etc.
In this article, we will learn about how to add elements to the end of a TreeSet in Java.
Syntax:
TreeSet.add(object element)
Program to add elements to the end of a TreeSet in Java
Below is the implementation to append elements to the end of a TreeSet.
Java
// Java Program to add elements to the end of a TreeSet import java.util.TreeSet;
public class TreeSetExample
{ public static void main(String[] args)
{
// Create a TreeSet
TreeSet<String> courseSet = new TreeSet<>();
// Add elements to the TreeSet
courseSet.add( "Java" );
courseSet.add( "Python" );
courseSet.add( "C++" );
// Print the TreeSet
System.out.println( "TreeSet elements: " + courseSet);
// Add elements to the end of TreeSet
courseSet.add( "DSA" );
courseSet.add( "Full Stack Web Development" );
// Print the TreeSet after adding elements
System.out.println( "TreeSet elements after adding: " + courseSet);
}
} |
Output
TreeSet elements: [C++, Java, Python] TreeSet elements after adding: [C++, DSA, Full Stack Web Development, Java, Python]
Explanation of the Program:
- In the above program, a TreeSet of Strings is created to store course names.
- Some course names are added to the TreeSet which sorts them automatically.
- The initial TreeSet elements are printed in sorted order.
- More courses are added and TreeSet keeps them sorted in insertion order.
- The final TreeSet after all additions is printed, still maintaining sorted order.
Note: TreeSet is automatically sorted, so the final output shows the elements in their natural order.