Tree Set Example

In the following example, we will use the TreeSet collection which stores its element in a tree and maintained the order of their element based on their values.

Tree Set Example

Tree Set Example

In the following example, we will use the TreeSet collection which stores its element in a tree and maintained the order of their element based on their values. The java.util.TreeSet class implements the set interface, TreeSet is derived from set interface and set interface is derived from collection its form a hierarchy. It uses all the methods derived from collection like add(), iterator() etc. TreeSet allow to store only unique element.

Features of  TreeSet  are as follows :

  • TreeSet allow only unique element, no duplicate is allowed.
  • It return the element in ascending order.
  • Comparator interface is used to alter the ordering.

 TreeSet uses methods of collection like add() to add the element into the specifies set, clear()  to remove all the element in this set, comparator() used to order the element in the set, first() return the first element in the set, last() return the last element in the set, iterator() return the element in the order, isEmpty() return true if the set contains no element, size() return the size of element, lower(E e) return the greatest element in the set less than the specified element etc.

Here is code for TreeSet example.

import java.util.Iterator;
import java.util.TreeSet;

public class Treeset 
   {
   public static void main(String[] args) 
      {
      // creating a TreeSet 
      TreeSet t = new TreeSet();
     
      // adding in the tree set
      t.add(10);
      t.add(9);
      t.add(2);
      t.add(121);
     
      // create ascending order
      Iterator itr;
      itr = t.iterator();
     
      // displaying the Tree set element
      System.out.println("Element in ascending order: ");     
      while (itr.hasNext()){
         System.out.println(itr.next() + " ");
      }
   }     
}

Output :  After compiling and executing the above program.

Download SourceCode