TreeSet Class in Java Tutorial with Example

TreeSet class implements Set interface. It extends AbstractSet class and implements NavigableSet interface.It has the following properties:

1. TreeSet implements Set interface so it does not allow duplicate values.
2. TreeSet sorts the elements in the ascending order.
3. TreeSet does not allow to insert heterogeneous elements. ClassCastException will be thrown if you try to add a heterogeneous element.
4. TreeSet doesn't allow to add null element.
5. TreeSet implementation is not synchronized. It can be synchronized explicitly by using
    SortedSet  s = Collections.synchronizedSortedSet(new TreeSet(...);


TreeSet Example


import java.util.*;
public class TreeSetExample {
    public static void main(String args[]) {
      // Create a TreeSet object
      TreeSet ts = new TreeSet();
     
      // Add elements to the TreeSet
      ts.add("C");
      ts.add("A");
      ts.add("B");
      ts.add("E");
      ts.add("F");
      ts.add("D");
      
      //Display TreeSet elements
      System.out.println(ts);

    }
}

Output
[A, B, C, D, E, F]


TreeSet Methods

TreeSet methods are as follows :

1. public boolean add(E e) : it adds the specified element to the set if it is not already present.
2. public void clear() : it removes all of the elements from the set.
3. public Object clone() : it returns the shallow copy of the TreeSet instance.
4. public boolean contains(Object o) : it returns true if the set contains the specified element.
5. public boolean isEmpty() : it returns true if the set contains no element.
6. public boolean remove(Object o) : it removes the specified element from the set if it is present.
7. public int size() : it returns the number of elements  in the set.

TreeSet Tutorials



  • TreeSet vs HashSet
  • How to Convert Array to TreeSet
  • How to Convert HashSet to TreeSet
  • TreeSet Interview Questions


  • References : TreeSet Oracle Docs

    About The Author

    Subham Mittal has worked in Oracle for 3 years.
    Enjoyed this post? Never miss out on future posts by subscribing JavaHungry