Java TreeSet Class


TreeSet belongs to the Java Collections Framework and serves as an implementation of the NavigableSet interface. A TreeMap forms the foundation for TreeSet which stores elements in sorted ascending order. TreeSet elements are stored in natural order or according to a custom comparator unlike an unordered HashSet.


Key Features

  • A sorted set arranges elements in their natural sequence such as numbers which are arranged from the smallest to the largest value.
  • No duplicates allowed
  • No null elements (throws NullPointerException)
  • Implements NavigableSet, SortedSet, and Set
  • Backed by a Red-Black Tree

Syntax

TreeSet set = new TreeSet<>(); 

Example

TreeSet numbers = new TreeSet<>();
 

Example

import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        TreeSet names = new TreeSet<>();

        // Add elements
        names.add("Zara");
        names.add("Alex");
        names.add("John");
        names.add("Emma");

        // Print sorted set
        System.out.println("Names: " + names); // [Alex, Emma, John, Zara]

        // Check and remove
        System.out.println("Contains John? " + names.contains("John"));
        names.remove("Zara");

        // Display final set
        for (String name : names) {
            System.out.println(name);
        }

        // Bounds
        System.out.println("First: " + names.first());
        System.out.println("Last: " + names.last());
    }
}

Note

  • Inserting null values into this data structure causes a NullPointerException.
  • The TreeSet performs slower than HashSet operations for adding, searching, and removing elements since it preserves a sorted sequence which requires O(log n) time complexity.
  • This data structure suits situations where automatic element sorting and range queries are required

TreeSet vs HashSet vs LinkedHashSet

Feature HashSet TreeSet LinkedHashSet
Order No order Sorted Insertion order
Duplicates Not allowed Not allowed Not allowed
Null allowed? Yes No Yes
Performance Fastest Slower Medium



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.