
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order.
The important points about the Java TreeSet class are:
TreeSet is being implemented using a binary search tree, which is self-balancing just like a Red-Black Tree. Therefore, operations such as a search, remove, and add consume O(log(N)) time. The reason behind this is there in the self-balancing tree. It is there to ensure that the tree height never exceeds O(log(N)) for all of the mentioned operations. Therefore, it is one of the efficient data structures in order to keep the large data that is sorted and also to do operations on it.
As already mentioned above, the TreeSet class is not synchronized. It means, if more than one thread concurrently accesses a tree set, and one of them accessing thread to modify it, then the synchronization must be done manually. It is usually done by doing some object synchronization techniques that encapsulates the set. However, in the case where no such object is found, then the set must be wrapped with the help of the Collections.synchronizedSet() method. It is advised to use the method during creation time in order to avoid the unsynchronized access of the set. The following code snippet shows the same.
As already mentioned above, the TreeSet class is not synchronized. It means if more than one thread concurrently accesses a tree set, and one of the accessing threads modify it, then the synchronization must be done manually. It is usually done by doing some object synchronization that encapsulates the set. However, in the case where no such object is found, then the set must be wrapped with the help of the Collections.synchronizedSet() method. It is advised to use the method during creation time in order to avoid the unsynchronized access of the set. The following code snippet shows the same.
As shown in the above diagram, the Java TreeSet class implements the NavigableSet interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical order.
The TreeSet class in Java is a crucial part of the Java Collections Framework, designed to store elements in a sorted and unique manner, ensuring no duplicates. Here are the key points about its hierarchical structure:
SortedSet Interface: TreeSet directly implements the SortedSet interface, which extends the basic Set interface. This interface introduces methods for operations that maintain an order among the elements and support range-view functionalities, essential for ordered data manipulation.
NavigableSet Interface: Positioned below the SortedSet, the NavigableSet interface adds advanced navigation capabilities. It allows TreeSet to retrieve elements based on their precise relation to others in the set, enhancing its functionality for efficient data querying and manipulation.
Efficiency: Backed by a TreeMap using a red-black tree structure, TreeSet performs fundamental operations like adding, removing, and checking the presence of elements with logarithmic time complexity, making it ideal for high-performance applications that require quick data processing.
Let's see the declaration for java.util.TreeSet class.
| Constructor | Description |
|---|---|
| TreeSet() | It is used to construct an empty tree set that will be sorted in ascending order according to the natural order of the tree set. |
| TreeSet(Collection<? extends E> c) | It is used to build a new tree set that contains the elements of the collection c. |
| TreeSet(Comparator<? super E> comparator) | It is used to construct an empty tree set that will be sorted according to given comparator. |
| TreeSet(SortedSet<E> s) | It is used to build a TreeSet that contains the elements of the given SortedSet. |
| Method | Description |
|---|---|
| boolean add(E e) | It is used to add the specified element to this set if it is not already present. |
| boolean addAll(Collection<? extends E> c) | It is used to add all of the elements in the specified collection to this set. |
| E ceiling(E e) | It returns the equal or closest greatest element of the specified element from the set, or null there is no such element. |
| Comparator<? super E> comparator() | It returns a comparator that arranges elements in order. |
| Iterator | It is used to iterate the elements in descending order. |
| NavigableSet | It returns the elements in reverse order. |
| E floor(E e) | It returns the equal or closest least element of the specified element from the set, or null there is no such element. |
| SortedSet | It returns the group of elements that are less than the specified element. |
| NavigableSet | It returns the group of elements that are less than or equal to (if, inclusive is true) the specified element. |
| E higher(E e) | It returns the closest greatest element of the specified element from the set, or null there is no such element. |
| Iterator | It is used to iterate the elements in ascending order. |
| E lower(E e) | It returns the closest least element of the specified element from the set, or null there is no such element. |
| E pollFirst() | It is used to retrieve and remove the lowest(first) element. |
| E pollLast() | It is used to retrieve and remove the highest(last) element. |
| Spliterator | It is used to create a late-binding and fail-fast spliterator over the elements. |
| NavigableSet | It returns a set of elements that lie between the given range. |
| SortedSet | It returns a set of elements that lie between the given range which includes fromElement and excludes toElement. |
| SortedSet | It returns a set of elements that are greater than or equal to the specified element. |
| NavigableSet | It returns a set of elements that are greater than or equal to (if, inclusive is true) the specified element. |
| boolean contains(Object o) | It returns true if this set contains the specified element. |
| boolean isEmpty() | It returns true if this set contains no elements. |
| boolean remove(Object o) | It is used to remove the specified element from this set if it is present. |
| void clear() | It is used to remove all of the elements from this set. |
| Object clone() | It returns a shallow copy of this TreeSet instance. |
| E first() | It returns the first (lowest) element currently in this sorted set. |
| E last() | It returns the last (highest) element currently in this sorted set. |
| int size() | It returns the number of elements in this set. |
Let's see a simple example of Java TreeSet.
FileName: TreeSet1.java
Output:
Ajay Ravi Vijay
Let's see an example of traversing elements in descending order.
FileName: TreeSet2.java
Output:
Traversing element through Iterator in descending order Vijay Ravi Ajay Traversing element through NavigableSet in descending order Vijay Ravi Ajay
Let's see an example to retrieve and remove the highest and lowest Value.
FileName: TreeSet3.java
Output:
Lowest Value: 12 Highest Value: 66
In this example, we perform various NavigableSet operations.
FileName: TreeSet4.java
Output:
Initial Set: [A, B, C, D, E] Reverse Set: [E, D, C, B, A] Head Set: [A, B, C] SubSet: [B, C, D, E] TailSet: [D, E]
In this example, we perform various SortedSetSet operations.
FileName: TreeSet5.java
Output:
Intial Set: [A, B, C, D, E] Head Set: [A, B] SubSet: [A, B, C, D] TailSet: [C, D, E]
Let's see a TreeSet example where we are adding books to the set and printing all the books. The elements in TreeSet must be of a Comparable type. String and Wrapper classes are Comparable by default. To add user-defined objects in TreeSet, you need to implement the Comparable interface.
FileName: TreeSetExample.java
Output:
101 Data Communications & Networking Forouzan Mc Graw Hill 4 121 Let us C Yashwant Kanetkar BPB 8 233 Operating System Galvin Wiley 6
If we add an object of the class that is not implementing the Comparable interface, the ClassCast Exception is raised. Observe the following program.
FileName: ClassCastExceptionTreeSet.java
Output:
Exception in thread "main" java.lang.ClassCastException: class Employee cannot be cast to class java.lang.Comparable (Employee is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap') at java.base/java.util.TreeMap.compare(TreeMap.java:1569) at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:776) at java.base/java.util.TreeMap.put(TreeMap.java:785) at java.base/java.util.TreeMap.put(TreeMap.java:534) at java.base/java.util.TreeSet.add(TreeSet.java:255) at ClassCastExceptionTreeSet.main(ClassCastExceptionTreeSet.java:52)
Explanation: In the above program, it is required to implement a Comparable interface. It is because the TreeSet maintains the sorting order, and for doing the sorting the comparison of different objects that are being inserted in the TreeSet is must, which is accomplished by implementing the Comparable interface.
| Feature | TreeSet | HashSet |
|---|---|---|
| Underlying Data Structure | Red-Black Tree | Hash Table |
| Ordering of Elements | Keeps elements sorted, which facilitates ordered traversal and quick-range searches. | Does not maintain any order; element arrangement is determined by the hash function. |
| Performance for Basic Operations | Somewhat increased temporal complexity; operations like add, delete, and contain are ?(log?)O(logN). | Constant-time complexity ?(1)O(1) for basic operations like add, delete, and contain, making it highly efficient. |
| Best Use Case | Better suited for applications requiring ordered data management, such as range queries or sequential access. | Ideal for scenarios where quick retrieval and manipulation are more important than element order. |
| Sorting | Automatically sorts elements according to their natural ordering or a specified comparator. | No sorting of elements; storage is hash-based. |
| Application Suitability | Preferred for applications where elements need to be maintained in a sorted manner. | More suitable for applications requiring fast access and where element order is not a concern. |
We request you to subscribe our newsletter for upcoming updates.