A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/treeset-in-java-with-examples/ below:

TreeSet in Java - GeeksforGeeks

TreeSet in Java

Last Updated : 08 Aug, 2025

Try it on GfG Practice

A TreeSet is a collection class that stores unique elements in a sorted order. It is part of java.util package that implements the SortedSet interface, and internally uses a Red-Black tree to maintain sorting.

Key Features of TreeSet

Example: Java Program Implementing TreeSet

Java
import java.util.TreeSet;

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

Output
TreeSet elements: []
Hierarchy Diagram of TreeSet TreeSet-Heirarchy

Note:

Constructors of TreeSet

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(): Creates an empty TreeSet that sorts elements in their natural order

Syntax:

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:

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:

TreeSet t = new TreeSet(Collection col); 

4. TreeSet(SortedSet): Creates a TreeSet containing the same elements and order as the specified SortedSet.

Syntax:

TreeSet t = new TreeSet(SortedSet s);

Various Operations over TreeSet

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.

1. Adding Elements

To add elements to a TreeSet, use the add() method. Elements are stored in ascending order, duplicates are ignored, and null values are not allowed.

Example: Java code to Illustrate Addition of Elements to TreeSet

Java
import java.util.*;
class GFG {

    public static void main(String[] args)
    {
        // Creating a Set interface with reference to TreeSet class
        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]
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 code to Illustrate Working of TreeSet by Accessing the Element of TreeSet

Java
import java.util.*;
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
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 Program to Illustrate Removal of Elements in a TreeSet

Java
import java.util.*;

class GFG {

    public static void main(String[] args)
    {
        // Creating an object of NavigableSet 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");
        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]
4. Iterating 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 Program to Illustrate Working of TreeSet

Java
import java.util.*;

class GFG {

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

StringBuffer does NOT implement the Comparable interface. Therefore, you must provide a custom Comparator to use StringBuffer objects in a TreeSet.

Example: Java code to illustrate How to Use StringBuffer in TreeSet with a Custom Comparator

Java
import java.util.*;

class Geeks {

    public static void main(String[] args)
    {
        // Creating a TreeSet with a custom Comparator
        Set<StringBuffer> ts = new TreeSet<>(new Comparator<StringBuffer>() {
            @Override
            public int compare(StringBuffer sb1, StringBuffer sb2) {
                return sb1.toString().compareTo(sb2.toString());
            }
        });

        // Adding elements to the TreeSet
        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"));

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

Output
[1, A, B, L, O, Z]
Methods of TreeSet

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

Method Description add(Object o) Adds element in sorted order; ignores duplicates. addAll(Collection c) Adds all elements from a collection; ignores duplicates.. 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.

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4