TreeSet in Java
TreeSet provides an implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like simple set with the exception that it stores elements in sorted format. Following are the features of TreeSet.
- TreeSet uses tree data structure for storage.
- Objects are stored in sorted, ascending order. But we can iterate in descending order using method TreeSet.descendingIterator().
- Access and retrieval times are very fast which make TreeSet an excellent choice for storage of large volume of data in sorted format.
- TreeSet doesn’t use hashCode() and equals() methods to compare it’s elements. It uses compare() (or compareTo()) method to determine the equality of two elements.
Important Methods of treeset class:
- boolean add(E e): This method adds the specified element to this set if it is not already present.
- E ceiling(E e): This method returns the least element in this set greater than or equal to the given element, or null if there is no such element.
- boolean contains(Object o): This method returns true if this set contains the specified element.
- E floor(E e): This method returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
- E pollFirst(): This method retrieves and removes the first (lowest) element, or returns null if this set is empty.
- E pollLast(): This method retrieves and removes the last (highest) element, or returns null if this set is empty.
- boolean remove(Object o): This method removes the specified element from this set if it is present.
The following is a very simple TreeSet implementation including TreeSet is sorting, iteration in a TreeSet, retrieving first and last element, and remove an element.
Tree set data: 10 39 61 87 Tree Set size: 4 First data: 10 Last data: 87 Data is removed from tree set Now the tree set contain: 10 39 87 Now the size of tree set: 3 Tree Set is empty.
Please refer TreeSet in Java with Examples for more details.
This article is contributed by Rishabh Mahrsee. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
My Personal Notes arrow_drop_up
Please Login to comment...