TreeSet in Java

  • The TreeSet class extends AbstractSet and implements set interface.
  • The TreeSet uses tree structure for internal storage.
  • The TreeSet stores objects in a sorted manner because TreeSet stores its elements in a tree structure.
  • In TreeSet, Access and retrieval times are quite fast.
  • The TreeSet value can get by Iterator interface.
  • The TreeSet provides basic operation such as add(), addAll(), first(), last(), contains(), remove() and size() methods.
  • TreeSet is not synchronized. If more than one thread wants to access it at the same time then it must be synchronized externally.
The following table demonstrates the constructors of TreeSet and corresponding methods.

Constructor
Meaning
TreeSet()
Constructs empty TreeSet Object.
TreeSet (Collection C)
Constructs a new set containing the elements of the given collection.
TreeSet (Comparator cmp)
Constructs empty set with sorted according to given comparator.
TreeSet (SortedSet sst)
Constructs new set that contains elements of the given sorted set.

The following program shows a simple use of TreeSet. 

Example:

/**
From SimpleTreeSet.java
*/

import java.util.TreeSet;

/**
 *
 * @author JavaHotSpot
 */

public class SimpleTreeSet
{
  public static void main(String args[])
  {
      TreeSet<String> tset = new TreeSet<String>();
      tset.add("Book0");
      tset.add("Book1");
      tset.add("Book2");
      tset.add("Book3");
      tset.add("Book4");
      tset.add("Book5");
      tset.add("Book6");
      System.out.println("The TreeSet elements are"+"\n"+tset);
  }
}

Output:
The TreeSet elements are
[Book0, Book1, Book2, Book3, Book4, Book5, Book6]


The following program shows a use of TreeSet with Iterator Interface.

Example:

/**
From TreeSetwithIterator.java
*/

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

/**
 *
 * @author JavaHotSpot
 */

public class TreeSetwithIterator
{
  public static void main(String args[])
  {
      String ss;
      TreeSet<String> tset = new TreeSet<String>();
      tset.add("Book0");
      tset.add("Book1");
      tset.add("Book2");
      tset.add("Book3");
      tset.add("Book4");
      tset.add("Book5");
      tset.add("Book6");
      System.out.println("The TreeSet elements are");
      Iterator it = tset.iterator();
      while(it.hasNext())
      {
          ss=(String)it.next();
          System.out.println(ss);
      }
  }
}

Output:
The TreeSet elements are
Book0
Book1
Book2
Book3
Book4
Book5