Java TreeSet Class

Category: Java   Tags: Java, Java Collection, Java Set Interface, Java TreeSet Class

TreeSet class extends AbstractSet and implements the NavigableSet interface. TreeSet is a generic class that has this declaration:

                                    public class TreeSet<E>
                                    extends AbstractSet<E>
                                    implements NavigableSet<E>, Cloneable, Serializable

Here, E specifies the type of object that this set will contain. The elements are ordered using their natural ordering, or by a Comparator provided at the creation time. The TreeSet classs provides guaranteed log(n) time cost for the basic operations: add, remove and contains.

The TreeSet class uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.


public TreeSet()
It constructs an empty TreeSet that will be sorted in ascending order according to the natural order of its elements.
public TreeSet(Comparator<? super E> comparator)
Constructs a new, empty TreeSet, sorted according to the specified comparator.
public TreeSet(Collection<? extends E> c)
Constructs a TreeSet that contains the elements of collection c.
public TreeSet(SortedSet<E> s)
Constructs a new TreeSet containing the elements of s and using the same ordering as the specified sorted set.

TreeSet is not synchronized. Therefore if multiple thread is accessing the set then it must synchronized externally. You can check out this post about synchronization. You can use Collections.synchronizedSortedSet also to synchronize the TreeSet:

                                    SortedSet s = Collections.synchronizedSortedSet(new TreeSet());

The returned iterator of this class are fail-fast i.e during iterating the TreeSet if you do any modification, it will throw ConcurrentModificationException exception. Here is one TreeSet example:


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

                            public class TreeSetExample {

                                public static void main(String[] args) {
                                    TreeSet<Integer> set = new TreeSet<>();
                                    System.out.println("Size: " + set.size());

                                    //Iterate the TreeSet
                                    System.out.println("TreeSet iteration: ");
                                    Iterator<Integer> iterator = set.iterator();
                                    while (iterator.hasNext()) {
                                        Integer element =;



                            Size: 3
                            TreeSet iteration:

As you can see that TreeSet keeps the data in sorted form.