When we work with data in Java, sometimes we need to store values in a sorted order without allowing duplicate values. Java provides a class called TreeSet for this purpose.
TreeSet is one of the most useful classes in the Java Collection Framework. It automatically arranges elements in ascending order and removes duplicate values. Because of these features, TreeSet is widely used in real-world applications where unique and sorted data is required.
In this blog, we will learn what TreeSet is, its features, constructors, methods, examples, advantages, disadvantages, and real-time use cases in simple English.
What is TreeSet in Java?
TreeSet is a class present in the java.util package. It implements the NavigableSet interface, which extends the SortedSet interface.
TreeSet stores only unique elements and automatically sorts them according to their natural ordering.
Package
import java.util.TreeSet;
Key Features of TreeSet
• Stores only unique elements.
• Automatically sorts elements in ascending order.
• Does not maintain insertion order.
• Duplicate values are not allowed.
• Null values are generally not allowed.
• Provides many navigation methods like higher(), lower(), first(), last(), ceiling(), and floor().
• Uses a Red-Black Tree internally.
Internal Working of TreeSet
TreeSet internally uses a Red-Black Tree, which is a self-balancing binary search tree. Whenever a new element is inserted:
1. TreeSet checks whether the element already exists.
2. If it is unique, it inserts the element.
3. The tree automatically balances itself.
4. Elements remain sorted all the time.
Because of this structure, searching, inserting, and deleting elements usually take O(log n) time.
Creating a TreeSet
import java.util.TreeSet;
public class Demo {
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(30);
System.out.println(numbers);
}
}
Output
[10, 20, 30, 40, 50]
Notice that although the numbers were inserted randomly, TreeSet sorted them automatically.
Duplicate Elements Example
import java.util.TreeSet;
public class Demo {
public static void main(String[] args) {
TreeSet<String> fruits = new TreeSet<>();
fruits.add("Apple");
fruits.add("Mango");
fruits.add("Apple");
fruits.add("Orange");
System.out.println(fruits);
}
}
Output
[Apple, Mango, Orange]
The duplicate value Apple is stored only once.
TreeSet Constructors
1. Default Constructor
TreeSet<Integer> set = new TreeSet<>();
Creates an empty TreeSet with natural sorting.
2. Using Comparator
TreeSet<Integer> set = new TreeSet<>(Collections.reverseOrder()); Stores elements in descending order.
3. From Another Collection
ArrayList<Integer> list = new ArrayList<>();
list.add(40);
list.add(10);
list.add(20);
TreeSet<Integer> set = new TreeSet<>(list);
System.out.println(set);
Output
[10, 20, 40]
Important Methods of TreeSet add()
Adds an element.
set.add(100);
remove()
Deletes an element.
set.remove(20);
contains()
Checks whether an element exists. System.out.println(set.contains(40)); Output
true
first()
Returns the smallest element.
System.out.println(set.first());
last()
Returns the largest element.
System.out.println(set.last());
higher()
Returns the next greater element.
System.out.println(set.higher(30));
lower()
Returns the previous smaller element.
System.out.println(set.lower(30));
ceiling()
Returns the given element if present; otherwise the next greater element. System.out.println(set.ceiling(35));
floor()
Returns the given element if present; otherwise the previous smaller element. System.out.println(set.floor(35));
pollFirst()
Removes and returns the first element.
System.out.println(set.pollFirst());
pollLast()
Removes and returns the last element.
System.out.println(set.pollLast());
clear()
Removes all elements.
set.clear();
Iterating Through TreeSet
Using enhanced for loop
TreeSet<String> cities = new TreeSet<>();
cities.add("Pune");
cities.add("Delhi");
cities.add("Mumbai");
cities.add("Nagpur");
for(String city : cities)
{
System.out.println(city);
}
Output
Delhi
Mumbai
Nagpur
Pune
TreeSet in Descending Order
import java.util.Collections;
import java.util.TreeSet;
public class Demo {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>(Collections.reverseOrder());
set.add(5);
set.add(3);
set.add(8);
set.add(1);
System.out.println(set);
}
}
Output
[8, 5, 3, 1]
TreeSet with Custom Objects
When storing custom objects, TreeSet needs to know how to compare them. Example:
class Student implements Comparable<Student>{
int id;
String name;
Student(int id,String name){
this.id=id;
this.name=name;
}
public int compareTo(Student s){
return this.id-s.id;
}
public String toString(){
return id+" "+name;
}
}
TreeSet<Student> students = new TreeSet<>();
students.add(new Student(103,"Riya"));
students.add(new Student(101,"Aman"));
students.add(new Student(102,"Neha"));
System.out.println(students);
Output
101 Aman
102 Neha
103 Riya
Difference Between HashSet, LinkedHashSet and TreeSet
Feature HashSet LinkedHashSet TreeSet Order No order Insertion order Sorted order Duplicate Not Allowed Not Allowed Not Allowed Performance Fastest Fast Slightly slower
Feature HashSet LinkedHashSet TreeSet Null Values One allowed One allowed Not allowed
Internal Structure
Hash Table Hash Table + Linked List Red-Black Tree
Real-Time Applications of TreeSet
TreeSet is useful in many real-world applications.
1. Student Roll Numbers
Schools can store unique roll numbers in sorted order.
2. Employee IDs
Companies can maintain employee IDs without duplicates.
3. Dictionary Applications
Words can be displayed alphabetically.
4. Online Ticket Booking
Seat numbers can be stored in sorted order.
5. Leaderboards
Scores or ranks can be managed efficiently.
6. Banking Systems
Unique account numbers can be maintained in sorted format.
7. Product Codes
Shopping websites can store product IDs without duplicates.
Advantages of TreeSet
• Automatically sorts data.
• Duplicate values are removed automatically. • Searching is efficient.
• Provides many navigation methods.
• Suitable for sorted collections.
Limitations of TreeSet
• Slower than HashSet because sorting is maintained.
• Does not preserve insertion order.
• Null values are generally not allowed.
• Random access is not available.
Best Practices
• Use TreeSet when you need sorted data.
• Use HashSet if sorting is not required and better performance is needed. • Implement Comparable or provide a Comparator for custom objects. • Avoid inserting null values.
• Choose TreeSet only when sorted and unique data is required.
Interview Questions
1. What is TreeSet?
TreeSet is a class in the Java Collection Framework that stores unique elements in sorted order.
2. Does TreeSet allow duplicate values?
No. Duplicate values are automatically ignored.
3. Does TreeSet maintain insertion order?
No. It maintains sorted order.
4. Which data structure does TreeSet use?
Red-Black Tree.
5. Can TreeSet store null values?
Generally, no.
6. What is the time complexity of add(), remove(), and contains()? The average time complexity is O(log n).
7. Which interface does TreeSet implement?
NavigableSet, which extends SortedSet.
Conclusion
TreeSet is one of the most useful collection classes in Java whenever sorted and unique data is required. It automatically arranges elements in ascending order, removes duplicate values, and provides powerful navigation methods for searching nearby elements. Although it is slightly slower than HashSet due to sorting, it is the right choice when data must always remain ordered.
For Java beginners, understanding TreeSet is important because it is commonly asked in interviews and frequently used in enterprise applications. By practicing the examples shared in this blog, you can confidently use TreeSet in your Java programs and choose the right collection based on your application’s requirements.
Author:
Aarti Choudhary
Related Links:
Do visit our channel to know more: SevenMentor
Aarti Choudhary
Expert trainer and consultant at SevenMentor with years of industry experience. Passionate about sharing knowledge and empowering the next generation of tech leaders.