TreeSet is an implementation class of NavigableSet interface which is a child interface of SortedSet. It is a class in the collection framework that stores and manipulates elements in some sorting order. It represents self-balancing binary tree as its underlying data structure which makes it a good choice for search and retrieving operations.
Syntax:
Set<T> set = new TreeSet<T>();
It stores elements in natural sorting order using compareTo() method of Comparable interface. It also allows custom sorting order with the help of compare() method of Comparator interface.
It provides various methods that are inherited from Navigable,SortedSet and Set interface.
1. It uses self balancing tree as its underlying data structure
2. It doesn’t allow Duplicate elements
3. It doesn’t preserve insertion order
4. It stores data in some sorting order
5. Only comparable or same type of elements are allowed
6. It is not thread safe
7. It provides non synchronised implementation of Set
TreeSet class uses self balancing binary search tree as its underlying data structure which makes it one of the efficient implementations for storing large data set in ordered manner. It takes logarithmic average and worst case time when it comes to perform basic operations such as add, delete and search.
It is also important to know that TreeSet provides non synchornized implementation which allow multiple threads to access a tree set object concurrently. It can lead to uncertain behaviour as more than one threads can operate on that object at the same time. It is possible to make a tree set synchronized. With the help of Collection.synchronizedSortedSet() method we can encapsulate a set in a synchronized object or wrapper.
Syntax :
Set<T> treeSet = new TreeSet<>(); Set synchronized = Collections.synchronziedSet(treeSet);
If a treeSet is non empty Set, then by default we are going to get null pointer exception while trying to insert null value. It occurs because of the comparison with other elements.
For empty TreeSet, null value can be accepted
There are four constructors support by TreeSet class.
1) TreeSet()
A default constructor that creates an empty tree set object with default natural sorting order
TreeSet<T> t = new TreeSet<T>()
2) TreeSet(Comparator c)
It creates an empty tree set instance with custom specified order defined using Comparator .
TreeSet<T> t = new TreeSet(Comparator c);
3) TreeSet(Collection obj)
It creates a tree set instance with the elements present in the collection object and order them in nature order.
TreeSet<T> t = new TreeSet<>(Collection obj)
4) TreeSet(SortedSet obj)
Similar to previous constructor, the constructor accepts a collection object which is in this case, is SortedSet and creates an tree set instance with all the elements present in that collection in natural order.
TreeSet<T> t = new TreeSet<T>(Sorted obj)
Method Name | Explanation |
---|---|
add(Object) | The method adds an element in a given set, returns false if one tries to add duplicate element |
addAll(CollectionObj) | It adds all the elements of the given collection in a given set |
clear() | It removes all elements from the given set |
contains(Object) | It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false |
containsAll(CollectionObj) | It returns true, if all the elements of the given collection exist in the set, otherwise false |
isEmpty() | It checks whether a set is empty or not. it returns if empty, other false |
iterator() | It provides iterator object to iterate through set |
remove(Object) | It removes the given object from the set, if present |
retainAll(CollectionObj) | It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object |
size() | It returns number of elements present in a set |
spliterator() | it returns spliterator object to iterate through set |
toArray() | It converts given set and returns array |
removeAll(CollectionObj) | It removes all the elements consisting in the collection object |
Method Name | Explanation |
---|---|
comparator() | Returns comparator object which is used to define custom sorting order on elements in the set or returns null if the set is using some natural order |
subSet(T from, T to) | It returns all the elements rangin from element "fromEle" to "toEle". If both the elements are same, then it would return empty set. It can throw IllegalArgumentException if the provided elements are not in range of the given set |
headSet(elementObj) | It returns all the elements lesser than the provided element. It can throw IllegalArgumentException if the provided elements are not in range of the given set |
tailSet(elementObj) | It returns all the elements greater than the provided element. It can throw IllegalArgumentException if the provided elements are not in range of the given set |
first() | It returns very first element from the given set |
last() | It returns last element from the given set |
Methods | Explanation |
---|---|
lower(element) | It returns greatest element that is lower than the given element |
higher(element) | It returns lowest element that is higher than the given element |
floor(element) | It returns greatest element that is lower than or equal to the given element |
ceiling(element) | It returns lowest element that is higher than or equal the given element |
pollFirst() | It returns and removes first element from the set |
pollLast() | It returns and removes last element from the set |
descendingSet() | It returns reverse view of the given set. |
If the empty tree set is created with default constructor, then the elements should be of same type and comparable, otherwise, ClassCastingException would be triggered by the Java compiler. Objects that implements Comparable interface are called comparable.
obj1.compareTo(obj 2)
If a custom implementation is required, we can use Comparator, not Comparable.
A tree set can have duplicate elements if we use Comparator to implement the sorting or insertion changes.
Program:
import java.util.*; public class SetExample implements Comparator<Integer>{ public static void main(String[] args) { Set<Integer> treeSet = new TreeSet<>(new SetExample()); // creating a treeSet instance that holds integers // Adding elements to linked hash set treeSet.add(5); treeSet.add(1); treeSet.add(2); treeSet.add(100); treeSet.add(101); // Iterating using for each Iterator iterator = treeSet.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } } @Override public int compare(Integer o1, Integer o2) { return o2-o1; } }
Output:
101 100 5 2 1