Introduction
The Java TreeSet class is one of the most powerful implementations of the Set interface in the Java Collection Framework. It stores unique elements like all Set implementations, but unlike HashSet and LinkedHashSet, it automatically stores elements in sorted order.
The TreeSet class belongs to the java.util package and is backed by a Red-Black Tree, which is a self-balancing binary search tree. Because of this internal structure, elements are always arranged in ascending order by default. You can also define a custom sorting order using a Comparator.
TreeSet is commonly used in applications where data needs to remain sorted automatically, such as leaderboards, ranking systems, dictionaries, contact lists, scheduling applications, and report generation.
TreeSet does not allow duplicate elements and does not allow null values because it needs to compare elements while maintaining the sorted order.
What is Java TreeSet?
A TreeSet is a collection that stores unique elements in sorted order.
By default:
- Numbers are sorted in ascending order.
- Strings are sorted alphabetically.
- Duplicate elements are automatically removed.
For example:
Input:
40
10
30
20
10
Output:
20
30
40
Notice that:
- Duplicate values are removed.
- Elements are automatically sorted.
Key Characteristics
- Stores unique elements
- Maintains sorted order
- Uses a Red-Black Tree internally
- Does not allow duplicate elements
- Does not allow null values
- Dynamic size
- Supports Generics
- Not synchronized
Java TreeSet Hierarchy
Object
│
AbstractCollection
│
AbstractSet
│
NavigableSet
│
TreeSet
The TreeSet class implements:
- Set
- SortedSet
- NavigableSet
- Collection
- Iterable
- Cloneable
- Serializable
Features of Java TreeSet
Some important features include:
- Stores unique elements
- Automatically sorts elements
- Dynamic size
- Supports natural ordering
- Supports custom ordering using Comparator
- Efficient searching
- Rich navigation methods
- Backed by a Red-Black Tree
Syntax
Import Statement
import java.util.TreeSet;
or
import java.util.*;
Creating a TreeSet
TreeSet<Integer> numbers = new TreeSet<>();
Using the Set interface:
Set<Integer> numbers = new TreeSet<>();
Programming to the interface is considered a best practice.
Constructors of TreeSet
1. Default Constructor
TreeSet<String>set = new TreeSe<>());
Creates an empty TreeSet that uses natural ordering.
2. Constructor with Comparator
TreeSet<Integer> set =
new TreeSet<>(Collections.reverseOrder());
Creates a TreeSet that stores elements in descending order.\
3. Constructor from Another Collection
List<Integer> list =
Arrays.asList(40, 10, 30, 20);
TreeSet<Integer> set =
new TreeSet<>(list);
System.out.println(set);
Output
Common Methods of TreeSet
| Method | Description |
|---|---|
| addFirst() | Adds an element |
| remove() | Removes an element |
| contains() | Checks whether an element exists |
| size() | Returns the number of elements |
| isEmpty() | Checks whether the Set is empty |
| clear() | Removes all elements |
| iterator() | Returns an iterator for traversal |
| addAll() | Adds all elements from another collection |
| removeAll() | Removes matching elements |
| retainAll() | Keeps only common elements |
Example 1: Creating a TreeSet
import java.util.*;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(40);
numbers.add(20);
numbers.add(10);
numbers.add(30);
System.out.println(numbers);
}
}
Output
Example 2: Removing Duplicate Elements
import java.util.*;
public class DuplicateExample {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(50);
numbers.add(20);
numbers.add(20);
numbers.add(10);
System.out.println(numbers);
}
}
Output
Duplicate elements are automatically ignored.
Example 3: Using first() and last()
import java.util.*;
public class FirstLastExample {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(10);
numbers.add(50);
numbers.add(30);
System.out.println(numbers.first());
System.out.println(numbers.last());
}
}
Output
50
Example 4: Descending Order
import java.util.*;
public class DescendingExample {
public static void main(String[] args) {
TreeSet<Integer> set =
new TreeSet<>(Collections.reverseOrder());
numbers.add(20);
numbers.add(50);
numbers.add(10);
System.out.println(numbers);
}
}
Output
Example 5: Iterating Through TreeSet
import java.util.*;
public class LoopExample {
public static void main(String[] args) {
TreeSet<Integer> course = new TreeSet<>();
courses.add("Java");
courses.add("Python");
courses.add("Spring");
for(String course : courses){
System.out.println(course);
}
}
}
Output
Python
Spring
How TreeSet Works Internally
Unlike HashSet, which uses a hash table, TreeSet uses a Red-Black Tree, a self-balancing binary search tree.
The process is:
- The element is inserted into the tree.
- The tree automatically balances itself.
- Elements remain sorted.
- Duplicate elements are rejected using comparison.
Because the tree stays balanced, searching, insertion, and deletion remain efficient even for large collections.
Navigable Methods
TreeSet provides additional navigation methods.
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
System.out.println(numbers.higher(20));
System.out.println(numbers.lower(20));
System.out.println(numbers.ceiling(25));
System.out.println(numbers.floor(25));
Output
10
30
20
These methods are useful for searching nearby values.
TreeSet vs HashSet vs LinkedHashSet
| Feature | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
| Duplicate Elements | No | No | No |
| Insertion Order | No | Yes | No |
| Sorted Order | No | No | Yes |
| Allows Null | Yes (one) | Yes (one) | Yes |
| Internal Structure | Hash Table | Hash Table + Linked List | Red-Black Tree |
| Performance | O(1) Average | O(1) Average | O(log n) |
Time Complexity
| Operation | Time Complexity |
|---|---|
| add() | O(1) (Average) |
| remove() | O(1) (Average) |
| contains() | O(1) (Average) |
| size() | O(1) |
| iteration | O(n) |
Although slower than HashSet, TreeSet guarantees sorted data.
Real-life Example
Imagine you’re building a leaderboard application.
Player scores are:
450
800
650
500
800
Using a TreeSet:
450
500
650
800
Benefits:
- Duplicate scores are removed.
- Scores remain sorted automatically.
Other real-world applications include:
- Student ranking systems
- Dictionary applications
- Contact management
- Event scheduling
- Product price lists
- Online gaming leaderboards
- Report generation
- Financial data analysis
Advantages of Java TreeSet
- Automatically sorts elements
- Prevents duplicate values
- Efficient searching
- Rich navigation methods
- Dynamic size
- Supports custom sorting
- Suitable for sorted collections
- Integrates well with the Java Collection Framework
Limitations of Java TreeSet
- Slower than HashSet for insertion and lookup
- Does not allow null values
- No index-based access
- Not synchronized
- Requires comparable elements or a Comparator
Common Mistakes
1. Adding Null Values
Incorrect:
TreeSet<Integer> set =
new TreeSet<>();
set.add(null);
This throws a NullPointerException.
2. Expecting Insertion Order
set.add(30);
set.add(10);
set.add(20);
Output:
20
30
TreeSet always sorts elements.
3. Adding Non-Comparable Objects
If custom objects do not implement the Comparable interface (or no Comparator is provided), a ClassCastException may occur.
4. Forgetting Generics
Incorrect:
TreeSet set = new TreeSet();
Correct:
TreeSet<Integer> set =
new TreeSet<>();
5. Using get() Method
Incorrect:
set.get(0);
TreeSet does not support index-based access.
Best Practices
- Program to the Set interface.
Set<Integer> Number =
new TreeSet<>();
- Use TreeSet when automatic sorting is required.
- Use a custom Comparator for custom sorting logic.
- Avoid storing null values.
- Ensure custom objects implement Comparable or provide a Comparator.
- Use Generics for compile-time type safety.
Conclusion
The Java TreeSet class is an excellent choice when your application requires unique elements to be stored in sorted order. Powered by a Red-Black Tree, it provides reliable performance for insertion, deletion, and searching while automatically maintaining the correct order of elements.
Although TreeSet is slightly slower than HashSet due to its sorting capabilities, it is ideal for applications involving rankings, reports, scheduling, and any scenario where ordered data is essential.