Creating and Populating a TreeSet in Java
Last Updated :
09 Feb, 2024
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
import java.util.TreeSet;
public class GfGTreeSet {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add( "C" );
treeSet.add( "Java" );
treeSet.add( "Python" );
treeSet.add( "Spring" );
treeSet.add( "Hibernate" );
System.out.println( "TreeSet: " + treeSet);
treeSet.add( "C++" );
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.
Share your thoughts in the comments
Please Login to comment...