Home > java > Treeset in java with Example

Treeset in java with Example

Treeset in java with Example

TreeSet in java, its object organize data in main memory by following binary tree concept. TreeSet class object always displays the data in sorted order. Access and retrieval times are too fast as compare to HashSet.

Methods of TreeSet class


TreeSet implements SortedSet so it has availability of all methods in Collection, Set, and SortedSet interfaces.

void add(Object o)Add given element into TreeSet
boolean addAll(Collection c)Add all elements of given Collection to the Set
void clear()Remove all the elements from Set
boolean contains(Object o)It will return true if specified element is present in TreeSet else it return false
Object first()It will return first element in TreeSet
Object last()It will return last element in TreeSet
SortedSet headSet(Object toElement)It will return elements of TreeSet which are less than the given element
SortedSet tailSet(Object fromElement)It will return elements of TreeSet which are are greater than or equal to the given element.
boolean isEmpty()It return true if Set is empty
Object clone()It return copy of Set
int size()It return size of Set or Number of element
Iterator iterator()it is Used to retrieve element from Set

Hierarchy of TreeSet


class TreeSet<Entry>extends AbstractSet<Entry> implements NavigableSet<Entry>, Cloneable, Serializable

In blow example, We will assign randomly but it will display in the sorted form.

Example of  TreeSet in java


import java.util.TreeSet;
import java.util.Iterator;
public class TreeSetDemo 
{
   public static void main(String args[]) 
   {
       // Create a tree set
       TreeSet<String> ts = new TreeSet<String>();

      // Add elements to the tree set
      ts.add("e1");
      ts.add("e2");
      ts.add("e7");
      ts.add("e4");
      ts.add("e6");
      ts.add("e5");
      ts.add("e7");
      System.out.println(ts);
      System.out.println("\nRetrive Treeset Data by Iterator Object");
      Iterator itr=ts.iterator();
      while(itr.hasNext())
      {
          System.out.println(itr.next());
      }
   }
}

OUTPUT

[e1, e2, e4, e5, e6, e7]

Retrive Treeset Data by Iterator Object
e1
e2
e4
e5
e6
e7
Admin
We are group of application developer and admin.We are providing good content of information about IT technology and services .

Leave a Reply

Your email address will not be published. Required fields are marked *