Back to Java
2026-01-235 min read

Java TreeSet

Learn Java TreeSet step by step with clear examples and exercises.

Why This Matters

Welcome to this full guide on Java TreeSet! In this tutorial, we will delve into the world of sorted sets and learn how to use the TreeSet data structure effectively. We'll cover why TreeSet is important, its prerequisites, core concepts, a worked example, common mistakes, practice questions, and frequently asked questions.

Importance of TreeSet

TreeSet is an essential part of the Java Collections Framework as it provides a sorted set that stores unique elements in a tree structure. It's useful when you need to maintain the order of elements while ensuring they are distinct. TreeSet can be particularly handy for tasks such as sorting data, implementing priority queues, and performing efficient range queries.

Prerequisites

Before diving into TreeSet, it is essential to have a good understanding of the following topics:

  1. Basic Java programming concepts (variables, methods, loops, etc.)
  2. Interfaces and classes in Java
  3. The Collections Framework in Java (Lists, Sets, Maps)
  4. Understanding of binary search trees
  5. Familiarity with Comparable interface and Comparator class
  6. Knowledge of exceptions in Java

Core Concept

TreeSet is a generic data structure that implements the SortedSet interface in Java. It maintains its elements in a self-balancing binary search tree called the Red-Black Tree. This ensures efficient insertion, deletion, and searching operations with logarithmic complexity (O(log n)).

Here's an example of creating a TreeSet:

import java.util.TreeSet;

public class Main {
public static void main(String[] args) {
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(1);
treeSet.add(3);
treeSet.add(2); // Since 2 is already present, it will not be added again
System.out.println(treeSet); // Output: [1, 2, 3]
}
}

In the above example, we create a TreeSet of integers and add elements to it. Since TreeSet stores unique elements in sorted order, when we try to add a duplicate element (2), it is automatically skipped.

Key Features of TreeSet

  1. Sorted set: Elements are stored in ascending order by default.
  2. Unique elements: Duplicate elements are not allowed and will be ignored during insertion.
  3. Balanced tree structure: Red-Black Tree ensures efficient operations with logarithmic complexity.
  4. Implementation of NavigableSet interface: Provides additional methods for range queries like floor, ceiling, higher, and lower.
  5. Automatic sorting: Elements are automatically sorted during insertion and deletion.
  6. Comparator support: Allows customizing the comparison logic by providing a Comparator object.

Worked Example

Let's consider a practical scenario where we have a set of student names, and we want to store them in a sorted manner using TreeSet:

import java.util.TreeSet;

public class Main {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("John");
treeSet.add("Sara");
treeSet.add("Mike");
treeSet.add("Lisa");
System.out.println(treeSet); // Output: [Lisa, Mike, Sara, John]
}
}

In this example, we create a TreeSet of strings and add student names to it. The output is sorted alphabetically.

Common Mistakes

  1. Forgetting to import the necessary package: Don't forget to import java.util.TreeSet at the beginning of your file.
  2. Adding duplicate elements: Since TreeSet stores unique elements, attempting to add a duplicate element will not modify the set.
  3. Using TreeSet for non-comparable types: If you try to create a TreeSet with non-comparable types (like custom objects), you'll need to implement the Comparable interface for your custom object class or provide a Comparator.
  4. Accessing elements by index: Since TreeSet does not maintain an ordered array, accessing elements by index will throw an IndexOutOfBoundsException. Instead, use iterators or stream operations for traversal.
  5. Not handling exceptions: When removing elements that do not exist in the TreeSet, it may result in an UnsupportedOperationException. You can catch this exception and handle it appropriately in your code.
  6. Improper usage of Comparator: If you provide a Comparator, ensure it follows the correct comparison logic to maintain the sorted order of elements.
  7. Incorrect implementation of Comparable interface: When implementing the Comparable interface for custom objects, make sure the compareTo() method is correctly defined and adheres to its contract.

Practice Questions

  1. Create a TreeSet of integers and perform common set operations like union, intersection, and difference with another TreeSet.
  2. Implement a priority queue using TreeSet in Java.
  3. Write a program to find the kth smallest element in a large dataset using TreeSet.
  4. Given an array of strings, write a method that returns a TreeSet containing only words with length greater than 5.
  5. Create a custom object class and implement the Comparable interface to sort a TreeSet of these objects based on a specific field.
  6. Implement a method that merges two sorted TreeSets into one using the union operation.
  7. Write a program to find the median of a large dataset using TreeSet.
  8. Implement a method that returns the frequency of each element in a TreeSet.
  9. Given a list of strings, write a method that converts it into a TreeSet and sorts the elements based on their length.
  10. Write a program to find the second smallest element in a TreeSet.

FAQ

  1. Can I add null values to TreeSet? Yes, but it's not recommended as it can lead to unexpected behavior and confusion when dealing with sorted elements.
  2. What happens if I try to remove an element that does not exist in the TreeSet? Attempting to remove a non-existent element will result in an UnsupportedOperationException.
  3. How do I iterate through the elements of a TreeSet? You can use the for-each loop or an iterator to traverse the elements in sorted order.
  4. Can I create a TreeSet with custom objects? Yes, but you'll need to implement the Comparable interface for your custom object class or provide a Comparator.
  5. How can I sort a TreeSet based on a specific field of my custom object class? Implement the Comparable interface for your custom object class and define the compareTo() method accordingly. Alternatively, you can provide a Comparator that compares objects based on the desired field.
  6. What is the time complexity of common operations in TreeSet? Insertion, deletion, and searching have an average time complexity of O(log n).
  7. How does TreeSet handle duplicates when using a custom Comparator? If you provide a Comparator that returns 0 for equal elements, duplicates will be allowed and maintained in the set.
  8. Can I use TreeSet to store objects with complex comparison logic? Yes, by providing a Comparator object that implements the desired comparison logic, you can use TreeSet with complex data types.
  9. How do I find the smallest or largest element in a TreeSet? You can use the first() and last() methods respectively to get the minimum and maximum elements from a TreeSet.
  10. Can I use TreeSet for storing primitive types like int or double? Yes, you can create a TreeSet of wrapper classes (Integer, Double) for primitive types. However, if you want to store primitives directly, consider using TreeMap instead, which allows direct storage of primitives with sorted keys.
Java TreeSet | Java | XQA Learn