Tutorials

Java Collection Framework


Java TreeSet


TreeSet is a class that implements Set interface and extends AbstractSet class.

TreeSet stores the element in sorted order.

By default, elements in TreeSet class is stored in ascending order.

 

Declaration of TreeSet class


public class TreeSet extends AbstractSet implements NavigableSet, Cloneable, Serializable 

Key feature of TreeSet

  • TreeSet contains only unique elements.
  • Maintains ascending order (by default). 
  • Access and retrival time is fast in TreeSet.

Create TreeSet in java

We can use any of the following constructor to create TreeSet in java.

  • TreeSet  mySet = new TreeSet();     
  • TreeSet  mySet = new TreeSet( Collection c);  
  • TreeSet  mySet = new TreeSet(Comparator c);
  • TreeSet  mySet = new TreeSet(SortedSet s);    

Simple Example:


package javaRadarTreeSet;

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

public class TreeSetExample {

      public static void main(String[] args) {

            //Create treeset
            TreeSet treeSet = new TreeSet();

            //Add elements to treeset
            treeSet.add("Omjit");
            treeSet.add("Krishna");
            treeSet.add("Mithilesh");
            treeSet.add("Manish");
            treeSet.add("Puja");
            treeSet.add("Shweta");
            treeSet.add("Rita");

            //Traverse the elements of treeset
            Iterator setIterator = treeSet.iterator();

            while(setIterator.hasNext()){

                  String element = setIterator.next();

                  System.out.println(element);

            }

      }

}

OUTPUT:

Krishna
Manish
Mithilesh
Omjit
Puja
Rita
Shweta

 

Now let’s look at different ways in which you can use the TreeSet that you created. 

Click on each link to read about them.

 

TreeSet operations

  • Sort the elements in TreeSet  --> (by default its sorted in ascending order)
  • Search element in TreeSet
  • Remove element from a particular index in TreeSet

 

Traverse TreeSet

  • Traverse TreeSet using Iterator
  • Traverse TreeSet using ListIterator
  • Traverse TreeSet using Enumeration


Please Share this page
Views : 72