How to Add or Append Elements to End of a TreeSet in Java?
Last Updated :
05 Feb, 2024
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
import java.util.TreeSet;
public class TreeSetExample
{
public static void main(String[] args)
{
TreeSet<String> courseSet = new TreeSet<>();
courseSet.add( "Java" );
courseSet.add( "Python" );
courseSet.add( "C++" );
System.out.println( "TreeSet elements: " + courseSet);
courseSet.add( "DSA" );
courseSet.add( "Full Stack Web Development" );
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.
Share your thoughts in the comments
Please Login to comment...