TreeSet Class in Java

TreeSet Class

  • TreeSet maintains the elements in ascending order. It doesn’t contain any duplicate value but it allows inserting null in the list.
  • TreeSet class extents the AbstractSet class and implements NavigableSet interface.

Example : Program to implement different methods in TreeSet

import java.util.*;
public class TreeSetDemo
{
      public static void main(String args[])
      {
            TreeSet<String> ts = new TreeSet<String>();
            System.out.println("Intial size of TreeSet: "+ts.size());
            
            //adding the elements
            ts.add("ZZ");
            ts.add("AA");
            ts.add("BB");
            ts.add("CC");
            ts.add("DD");
            ts.add("CC");

            //ts.add(null); gives NullPointerException
            System.out.println("TreeSet elements after adding: "+ts);
            System.out.println("TreeSet is empty: "+ts.isEmpty());
            System.out.println("Size of TreeSet : "+ts.size());

            //delete the elements
            ts.remove("BB");
            System.out.println("TreeSet elemnts after deletion: "+ts);
      }
}


Output:
Intial size of TreeSet: 0
TreeSet elements after adding: [AA, BB, CC, DD, ZZ]
TreeSet is empty: false
Size of TreeSet : 5
TreeSet elemnts after deletion: [AA, CC, DD, ZZ]