
Introduction to TreeSet in Java
Introduction to TreeSet in Java
In Java, the Collection Framework provides a well-structured way to store, manipulate, and retrieve groups of objects. Among the various collection classes available, TreeSet is widely used when we need to store unique elements in a sorted manner.
Unlike arrays, which have a fixed size and do not provide built-in sorting, TreeSet automatically manages sorting, uniqueness, and resizing. It is especially useful in applications where data must always remain ordered, and duplicates are not allowed.
In this blog, we will understand TreeSet in detail, including its working mechanism, features, methods, examples, advantages, and real-time use cases.
Introduction to TreeSet in Java. The following tutorial explains the concept of an ordered collection using the TreeSet and depicts its features, ordering logic, and use cases.
What is TreeSet in Java?
TreeSet is a class in Java that implements the Set interface and stores elements in ascending sorted order by default.
Since TreeSet is a part of the java.util package, it follows all the rules of a Set:
No duplicate elements
No guaranteed insertion order
Unique and ordered data storage
Key Characteristics of TreeSet
Duplicate elements are not allowed
Elements are stored in sorted order
Sorting can be natural or custom
Internally uses a Red-Black Tree
Null values are generally not allowed
Package Name
java.util.TreeSet
Java TreeSet Class Hierarchy
The TreeSet class follows the hierarchy below:
Object
↓
AbstractCollection
↓
AbstractSet
↓
SortedSet
↓
NavigableSet
↓
TreeSet
This hierarchy shows that TreeSet supports:
Set behavior
Sorting functionality
Navigation methods such as higher, lower, first, and last
How TreeSet Works Internally
Internally, TreeSet uses a Red-Black Tree, which is a self-balancing binary search tree.
Because of this internal structure:
Elements are always sorted
Tree remains balanced automatically
Searching, insertion, and deletion take O(log n) time complexity
Sorting Mechanism
TreeSet sorts elements in two ways:
Natural Ordering
Uses the Comparable interface
Example: Integer, String
Custom Ordering
Uses the Comparator interface
Example: Descending order sorting
Features of Java TreeSet
✔ Stores unique elements only
✔ Maintains sorted order
✔ Does not preserve insertion order
✔ Supports navigation methods
✔ Uses Red-Black Tree internally
✔ Allows fast searching
✔ Not synchronized (not thread-safe)
✔ Does not allow heterogeneous elements
Explore Other Demanding Courses
No courses available for the selected domain.
Important Methods of TreeSet
Method Description
add() Adds an element
remove() Removes an element
contains() Checks if element exists
size() Returns number of elements
first() Returns smallest element
last() Returns largest element
higher() Returns higher element
lower() Returns lower element
pollFirst() Removes first element
pollLast() Removes last element
isEmpty() Checks if TreeSet is empty
Java TreeSet Example – Basic Program
Example 1: TreeSet with Integer Values
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(50);
numbers.add(20);
numbers.add(10);
numbers.add(40);
numbers.add(20); // duplicate value
System.out.println(numbers);
}
}
Output:
[10, 20, 40, 50]
✔ Elements are automatically sorted
✔ Duplicate value is ignored
TreeSet Example with Strings
import java.util.TreeSet;
public class TreeSetStringExample {
public static void main(String[] args) {
TreeSet<String> courses = new TreeSet<>();
courses.add("Java");
courses.add("Python");
courses.add("C");
courses.add("Java");
System.out.println(courses);
}
}
Output:
[C, Java, Python]
TreeSet with Custom Sorting (Descending Order)
import java.util.*;
public class TreeSetDescendingExample {
public static void main(String[] args) {
TreeSet<Integer> ts =
new TreeSet<>(Collections.reverseOrder());
ts.add(10);
ts.add(50);
ts.add(30);
System.out.println(ts);
}
}
Output:
[50, 30, 10]
Advantages of TreeSet
✔ Automatically sorts elements
✔ No duplicate values
✔ Useful navigation methods
✔ Ideal for ordered and range-based data
Limitations of TreeSet
❌ Slower than HashSet
❌ Does not allow null values
❌ Not thread-safe
❌ Cannot store mixed data types
When to Use TreeSet?
Use TreeSet when:
Sorted output is required
Duplicate values must be avoided
Range operations are needed
Data order is more important than performance
Real-Time Use Cases of TreeSet
Ranking systems
Leaderboards
Sorted student marks
Product price lists
Sorted user IDs
Conclusion
The Java TreeSet class is a powerful collection that stores unique elements in sorted order. It uses a Red-Black Tree internally to ensure balance and efficient operations. While it may be slower than HashSet, TreeSet provides advanced sorting and navigation features that make it ideal for many real-world applications.
Do visit our channel to learn More: SevenMentor