The Wayback Machine - https://web.archive.org/web/20240822105501/https://www.geeksforgeeks.org/treeset-in-java-with-examples/
Open In App

TreeSet in Java

Last Updated : 19 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let us start with a simple Java code snippet that demonstrates how to create and use a TreeSet.

Java
import java.util.TreeSet;

public class TreeSetCreation {
    public static void main(String args[]) {
        // Create a TreeSet of Strings
        TreeSet<String> treeSet = new TreeSet<>();
        
        // Displaying the TreeSet (which is empty at this point)
        System.out.println("TreeSet elements: " + treeSet);
    }
}

Output
TreeSet elements: []

TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface

It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class.

Hierarchy Diagram of TreeSet

TreeSet In Java Collection

It can clearly be perceived from the above image that the navigable set extends the sorted set interface. Since a set doesn’t retain the insertion order, the navigable set interface provides the implementation to navigate through the Set. The class which implements the navigable set is a TreeSet which is an implementation of a self-balancing tree. Therefore, this interface provides us with a way to navigate through this tree. 

Note:

  • An object is said to be comparable if and only if the corresponding class implements a Comparable interface.
  • String, StringBuffer class and all the Wrapper classes already implements Comparable interface Hence, we DO NOT get a ClassCastException. But if we are creating TreeSet of user defined classes or any Java classes which does not implements comparable interface we will get ClassCastException. to solve this problem we can either implement Comparable to our user defined class or we can pass Comparator object in Constructor while creating the set.
  • For an empty tree-set, when trying to insert null as the first value, one will get NPE from JDK 7. From JDK 7 onwards, null is not at all accepted by TreeSet. However, up to JDK 6, null was accepted as the first value, but any insertion of more null values in the TreeSet resulted in NullPointerException. Hence, it was considered a bug and thus removed in JDK 7.
  • TreeSet serves as an excellent choice for storing large amounts of sorted information which are supposed to be accessed quickly because of its faster access and retrieval time.
  • The insertion of null values into a TreeSet throws NullPointerException because while insertion of null, it gets compared to the existing elements, and null cannot be compared to any value.

Internal Working of TreeSet in Java

TreeSet is basically an implementation of a self-balancing binary search tree like a Red-Black Tree. Therefore operations like add, remove, and search takes O(log(N)) time. The reason is that in a self-balancing tree, it is made sure that the height of the tree is always O(log(N)) for all the operations. Therefore, this is considered as one of the most efficient data structures in order to store the huge sorted data and perform operations on it. However, operations like printing N elements in the sorted order take O(N) time.

Now let us discuss Synchronized TreeSet prior moving ahead. The implementation of a TreeSet is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSortedSet method. This is best done at the creation time, to prevent accidental unsynchronized access to the set. It can be achieved as shown below as follows:

TreeSet ts = new TreeSet(); 
Set syncSet = Collections.synchronziedSet(ts); 

Constructors of TreeSet Class are as follows:

In order to create a TreeSet, we need to create an object of the TreeSet class. The TreeSet class consists of various constructors which allow the possible creation of the TreeSet. The following are the constructors available in this class:

1. TreeSet(): This constructor is used to build an empty TreeSet object in which elements will get stored in default natural sorting order.

Syntax: If we wish to create an empty TreeSet with the name ts, then, it can be created as: 

TreeSet ts = new TreeSet(); 


2. TreeSet(Comparator): This constructor is used to build an empty TreeSet object in which elements will need an external specification of the sorting order.

Syntax: If we wish to create an empty TreeSet with the name ts with an external sorting phenomenon, then, it can be created as:

TreeSet ts = new TreeSet(Comparator comp); 


3. TreeSet(Collection): This constructor is used to build a TreeSet object containing all the elements from the given collection in which elements will get stored in default natural sorting order. In short, this constructor is used when any conversion is needed from any Collection object to TreeSet object.

Syntax: If we wish to create a TreeSet with the name ts, then, it can be created as follows:

TreeSet t = new TreeSet(Collection col);  


4. TreeSet(SortedSet): This constructor is used to build a TreeSet object containing all the elements from the given sortedset in which elements will get stored in default natural sorting order. In short, this constructor is used to convert the SortedSet object to the TreeSet object.

Syntax: If we wish to create a TreeSet with the name ts, then, it can be created as follows:

TreeSet t = new TreeSet(SortedSet s);

Methods in TreeSet Class

Method in TreeSet Class are depicted below in tabular format which later on we will be implementing to showcase in the implementation part.

TreeSet implements SortedSet so it has the availability of all methods in Collection, Set, and SortedSet interfaces. Following are the methods in the Treeset interface. In the table below, the “?” signifies that the method works with any type of object including user-defined objects. 

MethodDescription
add(Object o)This method will add the specified element according to the same sorting order mentioned during the creation of the TreeSet. Duplicate entries will not get added.
addAll(Collection c)This method will add all elements of the specified Collection to the set. Elements in the Collection should be homogeneous otherwise ClassCastException will be thrown. Duplicate Entries of Collection will not be added to TreeSet.
ceiling?(E e)This method returns the least element in this set greater than or equal to the given element, or null if there is no such element.
clear()This method will remove all the elements.
clone()The method is used to return a shallow copy of the set, which is just a simple copied set.
Comparator comparator()This method will return the Comparator used to sort elements in TreeSet or it will return null if the default natural sorting order is used.
contains(Object o)This method will return true if a given element is present in TreeSet else it will return false.
descendingIterator?()This method returns an iterator over the elements in this set in descending order.
descendingSet?()This method returns a reverse order view of the elements contained in this set.
first()This method will return the first element in TreeSet if TreeSet is not null else it will throw NoSuchElementException.
floor?(E e)This method returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
headSet(Object toElement)This method will return elements of TreeSet which are less than the specified element.
higher?(E e)This method returns the least element in this set strictly greater than the given element, or null if there is no such element.
isEmpty()This method is used to return true if this set contains no elements or is empty and false for the opposite case.
Iterator iterator()Returns an iterator for iterating over the elements of the set.
last()This method will return the last element in TreeSet if TreeSet is not null else it will throw NoSuchElementException.
lower?(E e)This method returns the greatest element in this set strictly less than the given element, or null if there is no such element.
pollFirst?()This method retrieves and removes the first (lowest) element, or returns null if this set is empty.
pollLast?()This method retrieves and removes the last (highest) element, or returns null if this set is empty.
remove(Object o)This method is used to return a specific element from the set.
size()This method is used to return the size of the set or the number of elements present in the set.
spliterator()This method creates a late-binding and fail-fast Spliterator over the elements in this set.
subSet(Object fromElement, Object toElement)This method will return elements ranging from fromElement to toElement. fromElement is inclusive and toElement is exclusive.
tailSet(Object fromElement)This method will return elements of TreeSet which are greater than or equal to the specified element.

Various Operations over TreeSet in Java

Here we will be performing various operations over the TreeSet object to get familiar with the methods and concepts of TreeSet in java. Let’s see how to perform a few frequently used operations on the TreeSet. They are listed as follows:

  • Adding elements
  • Accessing elements
  • Removing elements
  • Iterating through elements

Now let us discuss each operation individually one by one later alongside grasping with the help of a clean java program.

Operation 1: Adding Elements

In order to add an element to the TreeSet, we can use the add() method. However, the insertion order is not retained in the TreeSet. Internally, for every element, the values are compared and sorted in ascending order. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null values are not accepted by the TreeSet.

Example:

Java
// Java code to Illustrate Addition of Elements to TreeSet

// Importing utility classes
import java.util.*;

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating a Set interface with
        // reference to TreeSet class
        // Declaring object of string type
        Set<String> ts = new TreeSet<>();

        // Elements are added using add() method
        ts.add("Geek");
        ts.add("For");
        ts.add("Geeks");

        // Print all elements inside object
        System.out.println(ts);
    }
}

Output
[For, Geek, Geeks]


Operation 2: Accessing the Elements

After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains(), first(), last(), etc. 

Example:

Java
// Java code to Illustrate Working of TreeSet by
// Accessing the Element of TreeSet

// Importing utility classes
import java.util.*;

// Main class 
class GFG {

    // Main driver method 
    public static void main(String[] args)
    {
        // Creating a NavigableSet object  with 
      // reference to TreeSet class 
        NavigableSet<String> ts = new TreeSet<>();

        // Elements are added using add() method
        ts.add("Geek");
        ts.add("For");
        ts.add("Geeks");

         // Printing the elements inside the TreeSet object 
        System.out.println("Tree Set is " + ts);

        String check = "Geeks";

        // Check if the above string exists in
        // the treeset or not
        System.out.println("Contains " + check + " "
                           + ts.contains(check));

        // Print the first element in
        // the TreeSet
        System.out.println("First Value " + ts.first());

        // Print the last element in
        // the TreeSet
        System.out.println("Last Value " + ts.last());

        String val = "Geek";

        // Find the values just greater
        // and smaller than the above string
        System.out.println("Higher " + ts.higher(val));
        System.out.println("Lower " + ts.lower(val));
    }
}

Output
Tree Set is [For, Geek, Geeks]
Contains Geeks true
First Value For
Last Value Geeks
Higher Geeks
Lower For


Operation 3: Removing the Values

The values can be removed from the TreeSet using the remove() method. There are various other methods that are used to remove the first value or the last value. 

Example:

Java
// Java Program to Illustrate Removal of Elements
// in a TreeSet

// Importing utility classes
import java.util.*;

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of NavigableSet
        // with reference to TreeSet class
        // Declaring object of string type
        NavigableSet<String> ts = new TreeSet<>();

        // Elements are added
        // using add() method
        ts.add("Geek");
        ts.add("For");
        ts.add("Geeks");
        ts.add("A");
        ts.add("B");
        ts.add("Z");

        // Print and display initial elements of TreeSet
        System.out.println("Initial TreeSet " + ts);

        // Removing a specific existing element inserted
        // above
        ts.remove("B");

        // Printing the updated TreeSet
        System.out.println("After removing element " + ts);

        // Now removing the first element
        // using pollFirst() method
        ts.pollFirst();

        // Again printing the updated TreeSet
        System.out.println("After removing first " + ts);

        // Removing the last element
        // using pollLast() method
        ts.pollLast();

        // Lastly printing the elements of TreeSet remaining
        // to figure out pollLast() method
        System.out.println("After removing last " + ts);
    }
}

Output
Initial TreeSet [A, B, For, Geek, Geeks, Z]
After removing element [A, For, Geek, Geeks, Z]
After removing first [For, Geek, Geeks, Z]
After removing last [For, Geek, Geeks]


Operation 4: Iterating through the TreeSet

There are various ways to iterate through the TreeSet. The most famous one is to use the enhanced for loop. and geeks mostly you would be iterating the elements with this approach while practicing questions over TreeSet as this is most frequently used when it comes to tree, maps, and graphs problems. 

Example:

Java
// Java Program to Illustrate Working of TreeSet

// Importing utility classes
import java.util.*;

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of Set with reference to
        // TreeSet class

        // Note: You can refer above media if geek
        // is confused in programs why we are not
        // directly creating TreeSet object
        Set<String> ts = new TreeSet<>();

        // Adding elements in above object
        // using add() method
        ts.add("Geek");
        ts.add("For");
        ts.add("Geeks");
        ts.add("A");
        ts.add("B");
        ts.add("Z");

        // Now we will be using for each loop in order
        // to iterate through the TreeSet
        for (String value : ts)

            // Printing the values inside the object
            System.out.print(value + ", ");

        System.out.println();
    }
}

Output
A, B, For, Geek, Geeks, Z, 

Features of a TreeSet

  • TreeSet implements the SortedSet interface. So, duplicate values are not allowed.
  • Objects in a TreeSet are stored in a sorted and ascending order.
  • TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
  • If we are depending on the default natural sorting order, the objects that are being inserted into the tree should be homogeneous and comparable. TreeSet does not allow the insertion of heterogeneous objects. It will throw a classCastException at Runtime if we try to add heterogeneous objects.
  • The TreeSet can only accept generic types which are comparable.
    For example, the StringBuffer class implements the Comparable interface.
Java
// Java code to illustrate What if Heterogeneous 
// Objects are Inserted

// Importing all utility classes
import java.util.*;

// Main class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Object creation
        Set<StringBuffer> ts = new TreeSet<>();

        // Adding elements to above object
        // using add() method
        ts.add(new StringBuffer("A"));
        ts.add(new StringBuffer("Z"));
        ts.add(new StringBuffer("L"));
        ts.add(new StringBuffer("B"));
        ts.add(new StringBuffer("O"));
        ts.add(new StringBuffer(1));

        // Note: StringBuffer implements Comparable
        // interface

        // Printing the elements
        System.out.println(ts);
    }
}

Output
[, A, B, L, O, Z]


Similar Reads

TreeSet size() Method in Java
The Java.util.TreeSet.size() method is used to get the size of the Tree set or the number of elements present in the Tree set. Syntax: Tree_Set.size() Parameters: The method does not take any parameter. Return Value: The method returns the size or the number of elements present in the Set. Below program illustrates the use of Java.util.TreeSet.size
1 min read
TreeSet iterator() Method in Java
The Java.util.TreeSet.iterator() method is used to return an iterator of the same elements as that of the TreeSet. The elements are returned in random order from what was present in the Tree set. Syntax: Iterator iterate_value = Tree_Set.iterator(); Parameters: The function does not take any parameter. Return Value: The method iterates over the ele
1 min read
TreeSet remove() Method in Java
The Java.util.TreeSet.remove(Object O) method is to remove a particular element from a Tree set. Syntax: TreeSet.remove(Object O) Parameters: The parameter O is of the type of Tree set and specifies the element to be removed from the set. Return Value: This method returns True if the element specified in the parameter is initially present in the Se
1 min read
TreeSet pollFirst() method in Java
The pollFirst() method of TreeSet in Java is used to retrieves and removes the first (lowest) element, or returns null if this TreeSet is empty. Syntax: E pollFirst() Where, E is the type of elements maintained by this TreeSet container. Parameters: This function does not accepts any parameter. Return Type:It returns the first element of the Treese
3 min read
Job Sequencing Problem using TreeSet in JAVA
Given an array of jobs where every job has a deadline and associated profit (if the job is finished before the deadline). It is also given that every job takes a single unit of time, so the minimum possible deadline for any job is 1. How to maximize total profit if only one job can be scheduled at a time. Examples: Input : Four Jobs with following
3 min read
TreeSet subSet() Method in Java
The java.util.TreeSet.subSet() is used to return a subset of the existing TreeSet within a range mentioned in the parameter. The method takes in an upper limit and a lower limit and returns all the elements mentioned in the range. The lower limit is included if the element is present within the set and the upper limit is excluded. Basically, it tak
3 min read
TreeSet tailSet() Method in Java
The java.util.TreeSet.tailSet() method is used to set a point of start for a tree set, to return all the elements greater than the element passed as parameter mentioned to the method in a sorted manner including the element(if the element is mentioned in the tree). Syntax: TreeSet tail_set.tailSet(Object element) Parameters: The parameter element i
3 min read
TreeSet headSet() Method in Java With Examples
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. The headSet()
4 min read
TreeSet last() Method in Java
The Java.util.TreeSet.last() method is used to return the last of the element of a TreeSet. The last element here is being referred to the highest of the elements in the set. If the elements are of integer types, then the largest integer is returned. If the elements are of the string types, then the elements are checked in the alphabetical order an
3 min read
TreeSet first() Method in Java
The Java.util.TreeSet.first() method is used to return the first of the element of a TreeSet. The first element here is being referred to the lowest of the elements in the set. If the elements are of integer types then the smallest integer is returned. If the elements are of the string types then the elements are checked in the alphabetical order a
3 min read
TreeSet isEmpty() Method in Java
The Java.util.TreeSet.isEmpty() method is used to check and verify if a TreeSet is empty or not. It returns True if the TreeSet is empty else it returns False. Syntax: Tree_Set.isEmpty() Parameters: The method does not take any parameter Return Value: The function returns True if the set is empty else it returns False. Below program illustrate the
1 min read
TreeSet contains() Method in Java With Examples
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. This class pr
3 min read
TreeSet clone() Method in Java
The Java.util.TreeSet.clone() method is used to return a shallow copy of the mentioned tree set. It just creates a copy of the set. Syntax: Tree_Set.clone() Parameters: The method does not take any parameters. Return Value: The function just returns a copy of the TreeSet. Below program illustrates the use of Java.util.TreeSet.clone() method: // Jav
1 min read
TreeSet clear() Method in Java
The Java.util.TreeSet.clear() method is used to remove all the elements from a TreeSet. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing TreeSet. Syntax: Tree_Set.clear() Parameters: The method does not take any parameter R
1 min read
TreeSet addAll() Method in Java
The java.util.TreeSet.addAll(Collection C) method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order. Syntax: boolean addAll(Collection C) Parameters: The parameter C is a collection of any type that is to be added to the tree set. Return Valu
2 min read
TreeSet add() Method in Java
The Java.util.TreeSet.add() method in Java TreeSet is used to add a specific element into a TreeSet. The function adds the element only if the specified element is not already present in the set else the function return False if the element is not present in the TreeSet. Syntax: Tree_Set.add(Object element) Parameters: The parameter element is of t
1 min read
TreeSet comparator() Method in Java with Examples
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. The comparato
3 min read
HashSet vs TreeSet in Java
When it comes to discussing differences between Set the firstmost thing that comes into play is the insertion order and how elements will be processed. HashSet in java is a class implementing the Set interface, backed by a hash table which is actually a HashMap instance. This class permits the null element. The class also offers constant time perfo
5 min read
TreeSet descendingSet() method in Java with Examples
The descendingSet() method of java.util.TreeSet&lt;E&gt; class is used to return a reverse order view of the elements contained in this set. The descending set is backed by this set, so changes to the set are reflected in the descending set, and vice-versa. If either set is modified while an iteration over either set is in progress (except through
2 min read
TreeSet floor() method in Java with Examples
The floor() method of java.util.TreeSet&lt;E&gt; class is used to return the greatest element in this set less than or equal to the given element, or null if there is no such element. Syntax: public E floor(E e) Parameters: This method takes the value e as a parameter which is to be matched. Return Value: This method returns the greatest element le
2 min read
TreeSet ceiling() method in Java with Examples
The ceiling() method of java.util.TreeSet&lt;E&gt; class is used to return the least element in this set greater than or equal to the given element, or null if there is no such element. Syntax: public E ceiling(E e) Parameters: This method takes the value e as a parameter which is to be matched. Return Value: This method returns the least element g
2 min read
TreeSet higher() method in Java with Examples
The higher(E ele) method of TreeSet class in Java is used to return the least element in this set which is strictly greater than the given element ele. If no such element is there then this method returns NULL. Here, E is the type of element maintained by this TreeSet collection. Syntax: public E higher(E ele) Parameters:It takes only one parameter
2 min read
TreeSet lower() method in Java
The lower(E ele) method of TreeSet class in Java is used to return the greatest element in this set which is strictly less than the given element. If no such element exists in this TreeSet collection then this method returns a NULL. Here, E is the type of the elements maintained by this collection. Syntax: public E lower(E ele) Parameters: It takes
2 min read
TreeSet pollLast() method in Java with Example
The pollLast() method of Java.util.concurrent.TreeSet is an in-built function in Java which returns retrieves and removes the last (highest) element, or returns null if this set is empty. Syntax: public E pollLast() Return Value: The function returns retrieves and removes the last (highest) element, or returns null if this set is empty. Below progr
2 min read
TreeSet equals() method in Java with Example
The equals() method of java.util.TreeSet class is used to compare the specified object with this set for equality. Returns true if and only if the specified object is also a set, both sets have the same size, and all corresponding pairs of elements in the two sets are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2))
2 min read
TreeSet toArray(T[]) method in Java with Example
The toArray(T[]) method method of TreeSet class in Java is used to form an array of the same elements as that of the TreeSet. It returns an array containing all of the elements in this TreeSet in the correct order; the run-time type of the returned array is that of the specified array. If the TreeSet fits in the specified array, it is returned ther
4 min read
TreeSet toArray() method in Java with Example
The toArray() method of Java TreeSet is used to form an array of the same elements as that of the TreeSet. Basically, it copies all the element from a TreeSet to a new array. Syntax: Object[] arr = TreeSet.toArray() Parameters: The method does not take any parameters. Return Value: The method returns an array containing the elements similar to the
2 min read
TreeSet retainAll() method in Java with Example
The retainAll() method of java.util.TreeSet class is used to retain from this set all of its elements that are contained in the specified collection. Syntax: public boolean retainAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be retained from this set. Returns Value: This method returns true if th
3 min read
TreeSet removeAll() method in Java with Example
The removeAll() method of java.util.TreeSet class is used to remove from this set all of its elements that are contained in the specified collection. Syntax: public boolean removeAll(Collection c) Parameters: This method takes collection c as a parameter containing elements to be removed from this set. Returns Value: This method returns true if thi
3 min read
TreeSet hashCode() method in Java with Example
The hashCode() method of TreeSet in Java is used to get the hashCode value for this instance of the TreeSet. It returns an integer value which is the hashCode value for this instance of the TreeSet. Syntax: public int hashCode() Parameters: This function has no parameters. Returns: The method returns an integer value which is the hashCode value for
2 min read
three90RightbarBannerImg