Java TreeSet


The TreeSet class in Java is part of the Java Collections Framework and implements the NavigableSet interface. It is a collection of elements that are ordered based on their natural ordering or according to a specified comparator. The elements in a TreeSet are always sorted, and duplicates are not allowed, making it ideal for storing unique, ordered elements.


Key Features of TreeSet

  • Ordered: The elements in a TreeSet are sorted either according to their natural ordering (if they implement the Comparable interface) or by a custom comparator (if provided).
  • Unique Elements: Like any set, TreeSet does not allow duplicate elements.
  • Efficient Operations: TreeSet provides log(n) time complexity for basic operations such as add, remove, and contains due to its underlying data structure, a Red-Black tree.
  • NavigableSet Methods: Since TreeSet implements the NavigableSet interface, it offers methods like lower(), floor(), ceiling(), higher(), and descendingIterator() for efficient navigation.

Methods of TreeSet

Here are some key methods in the TreeSet class:

  1. add(E e): Adds an element to the set, ensuring that the set remains ordered. It returns false if the element already exists.
  2. remove(Object o): Removes the specified element from the set.
  3. contains(Object o): Checks if the set contains the specified element.
  4. pollFirst(): Removes and returns the first (lowest) element of the set, or null if the set is empty.
  5. pollLast(): Removes and returns the last (highest) element of the set, or null if the set is empty.
  6. subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive): Returns a view of the portion of the set whose elements are greater than or equal to fromElement and less than (or equal to, based on the boolean values) toElement.
  7. descendingIterator(): Returns an iterator that traverses the set in reverse order.

Example Code: Using TreeSet in Java

Let's dive into some sample code demonstrating how to use the TreeSet class.

import java.util.*;

public class TreeSetExample {
    public static void main(String[] args) {
        // Creating a TreeSet
        TreeSet<Integer> treeSet = new TreeSet<>();

        // Adding elements to the TreeSet
        treeSet.add(10);
        treeSet.add(5);
        treeSet.add(15);
        treeSet.add(20);
        treeSet.add(30);

        // Printing the TreeSet
        System.out.println("TreeSet: " + treeSet);

        // Checking if an element is present
        System.out.println("Does the TreeSet contain 15? " + treeSet.contains(15));

        // Using pollFirst() to remove and get the first element
        System.out.println("Removed first element: " + treeSet.pollFirst());

        // Using pollLast() to remove and get the last element
        System.out.println("Removed last element: " + treeSet.pollLast());

        // Using descendingIterator() to iterate in reverse order
        Iterator<Integer> descendingIterator = treeSet.descendingIterator();
        System.out.print("Descending order: ");
        while (descendingIterator.hasNext()) {
            System.out.print(descendingIterator.next() + " ");
        }

        // Creating a subset using subSet()
        NavigableSet<Integer> subSet = treeSet.subSet(10, true, 30, false);
        System.out.println("\nSubset from 10 (inclusive) to 30 (exclusive): " + subSet);
    }
}

Explanation of the Code:

  • We create a TreeSet object and add some integers to it.
  • The contains() method checks if a particular element exists in the set.
  • We use the pollFirst() and pollLast() methods to remove and retrieve the first and last elements from the set.
  • The descendingIterator() method is used to iterate through the set in reverse order.
  • The subSet() method is used to create a view of the elements in a specified range, including/excluding elements as needed.

Sample Output:

TreeSet: [5, 10, 15, 20, 30]
Does the TreeSet contain 15? true
Removed first element: 5
Removed last element: 30
Descending order: 20 15 10 
Subset from 10 (inclusive) to 30 (exclusive): [10, 15, 20]

Practical Use Cases of TreeSet

  1. Maintaining a Sorted List of Unique Elements: TreeSet is ideal when you need to keep a collection of unique, sorted elements and need efficient access to the lowest or highest element.
  2. Range Queries: With methods like subSet() and tailSet(), TreeSet is perfect for quickly retrieving a subset of elements within a given range.
  3. Leaderboard Systems: In applications such as gaming or competitive programming, where player scores need to be stored in a sorted order, a TreeSet can help manage the leaderboard.
  4. Event Scheduling: TreeSet can be used in event scheduling systems where events need to be stored in chronological order, and operations like finding the next upcoming event are necessary.