TreeSet class implements the Set interface and stores the data in tree structure. The values are stored in sorted and ascending oreder. It is quite fast in retrieval of elements. This makes TreeSet is most prefered choice for storing the large amount of data in sorted order and want to retrieve it fast. This supports the four variant of constructors:
- TreeSet( )
- TreeSet(Collection col)
- TreeSet(Comparator comparator)
- TreeSet(SortedSet set)
TreeSet Methods
- void add(Object o) –> This method adds the new element to set if it is not already present
- boolean addAll(Collection c) –> Takes collection and adds all the elements in the collection to this set
- void clear() –> Clears or removes all the elements from the set
- Object clone() –> Returns a shallow copy of this TreeSet instance
- Comparator comparator() –> This method returns the comparator instance used for this TreeSet
- boolean contains(Object o) –> This method returns true if this set contains the specified element
- Object first() –> This method returns the first element in the sorted set
- SortedSet headSet(Object toElement) –> This method returns the lower elements subset by checking the matching to element value
- boolean isEmpty() –> This method returns true if this set contains no elements and empty.
- Iterator iterator() –> Returns an iterator over the elements in this set.
- Object last() –> This method returns the last element in the sorted set
- boolean remove(Object o) –> This method removes the given element from this set if it is found
- int size() –> This method returns the number of elements in this set
- SortedSet subSet(Object fromElement, Object toElement) –> This method returns the subset by checking the matching from and to element values
- SortedSet tailSet(Object fromElement) –> This method returns the subset by checking the matching from element value
TreeSet Example
package javabeat.net.core; import java.util.TreeSet; public class TreeSetExample { public static void main(String args[]){ TreeSet<String> treeSet = new TreeSet<String>(); treeSet.add("Element 1"); treeSet.add("Element 3"); treeSet.add("Element 5"); treeSet.add("Element 2"); treeSet.add("Element 4"); System.out.println("Checking 'Element 2' : "+treeSet.contains("Element 2")); System.out.println("Printing TreeSet : "+treeSet); System.out.println("Removing 'Element 2' : "+treeSet.remove("Element 2")); System.out.println("Checking 'Element 2' : "+treeSet.contains("Element 2")); System.out.println("Printing TreeSet : "+treeSet); } }
Output for the above example will be:
Checking 'Element 2' : true Printing TreeSet : [Element 1, Element 2, Element 3, Element 4, Element 5] Removing 'Element 2' : true Checking 'Element 2' : false Printing TreeSet : [Element 1, Element 3, Element 4, Element 5]