TreeSet is a part of the Java Collections Framework and implements the Set interface, which means it doesn’t allow duplicate elements. However, the key feature of a TreeSet is that it stores the elements in a sorted order (ascending by default). It is based on a TreeMap, meaning it uses a Red-Black tree to store elements.
Features
- Sorted Order: Elements are stored in ascending order by default. You can also provide a custom order using a comparator.
- No Duplicates: Unlike lists, a
TreeSet
does not allow duplicate values. If an attempt to add a duplicate is made, it is ignored. - Efficient Operations: Operations like add, remove, and contains are performed in log(n) time complexity.
- NavigableSet:
TreeSet
implements theNavigableSet
interface, which allows navigating the set using methods likelower()
,higher()
, etc.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args) { // Creating a TreeSet of Integers TreeSet<Integer> set = new TreeSet<>(); // Adding elements to the TreeSet set.add(10); set.add(5); set.add(20); set.add(15); // Printing the TreeSet System.out.println("TreeSet: " + set); // Output will be sorted: [5, 10, 15, 20] // Using NavigableSet methods System.out.println("First Element: " + set.first()); // 5 System.out.println("Last Element: " + set.last()); // 20 // Trying to add a duplicate element set.add(10); // Duplicate will be ignored System.out.println("TreeSet after trying to add duplicate: " + set); // [5, 10, 15, 20] } } |
Use Cases
- Unique Sorted Data: If you need a collection that stores unique elements in a specific order, a
TreeSet
is ideal. - Range Queries: Due to its navigability,
TreeSet
is useful for tasks where you need to find elements within a certain range, or locate the closest higher or lower elements. - Maintaining Order: If maintaining an ordered list of elements is essential (like a leaderboard or ranking system),
TreeSet
is the perfect choice.