VOOZH about

URL: https://www.geeksforgeeks.org/java/add-or-append-elements-to-end-of-a-treeset-in-java/

⇱ How to Add or Append Elements to End of a TreeSet in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Add or Append Elements to End of a TreeSet in Java?

Last Updated : 23 Jul, 2025

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.


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.

Comment