Open In App

Creating and Populating a TreeSet in Java

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, TreeSet is a pre-defined class that can be used to implement the Set interface and it is a part of the Java collection framework TreeSet is a NavigableSet implementation based on the TreeMap. TreeSet follows the natural order which means elements can be stored in sorted order and it cannot allow the duplicate elements into the TreeSet.

In this article, we will learn how to create a TreeSet in Java and add elements to it.

Syntax for creating a TreeSet:

// Creating a TreeSet of Strings
TreeSet<String> treeSet = new TreeSet<>();

Step-by-step implementation:

  • Create the class named the GfGTreeSet and implement the logic into the main method.
  • Create the TreeSet of string names as the treeset and import the related packages into the program.
  • Using TreeSet object to add the elements into the TreeSet with the help of the add() method.
  • Print the result TreeSet of Strings
  • Then add new elements into the TreeSet.
  • Print the result TreeSet after trying to add the new elements into the TreeSet.

Program to Create a TreeSet and Add Elements to it in Java

Below is the program to create and then add elements to a TreeSet:

Java




// Java program to create a TreeSet and add elements to it
import java.util.TreeSet;
public class GfGTreeSet {
    //main method
    public static void main(String[] args) {
        // create a TreeSet of Strings
        TreeSet<String> treeSet = new TreeSet<>();
  
        // adding elements to the TreeSet
        treeSet.add("C");
        treeSet.add("Java");
        treeSet.add("Python");
        treeSet.add("Spring");
        treeSet.add("Hibernate");
  
        // display the elements in the TreeSet
        System.out.println("TreeSet: " + treeSet);
  
        // adding a new element 
        treeSet.add("C++");
  
        // display the elements again after adding a new element
        System.out.println("Elements in TreeSet after adding a new element: " + treeSet);
    }
}


Output

TreeSet: [C, Hibernate, Java, Python, Spring]
Elements in TreeSet after adding a new element: [C, C++, Hibernate, Java, Python, Spring]

Explanation of the Program:

  • The above program is the example of the creation of the TreeSet and adding elements into the treeset and it is easy to implement the program.
  • First Create the TreeSet, after that adding elements into the treeSet using add() method.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads