Open In App

Creating and Populating a TreeSet in Java

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:

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

Article Tags :