Open In App

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

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.

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 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:

Note: TreeSet is automatically sorted, so the final output shows the elements in their natural order.

Article Tags :