TreeSet in Java

In this tutorial, we will learn about TreeSet in Java and how to use it.

TreeSet extends AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order and uses a tree for storage. It further extends the Set Interface due to which it holds only unique objects.

Some points to remember about TreeSet in Java:

  • TreeSet contains unique elements.
  • TreeSet maintains ascending order.
  • TreeSet doesn’t allow NULL element.
  • TreeSet is non-synchronized.

Creating TreeSet in Java:

Let’s see how to create TreeSet in Java:

Set<T> animals = new TreeSet<>();

Here, “T” indicates the type of a TreeSet. For example,

// create Integer type TreeSet
Set<Integer> obj = new TreeSet<>();

// create String type TreeSet
Set<String> obj = new TreeSet<>();

TreeSet Declaration:

Below is the java.util.TreeSet class declaration present in the JDK:

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable {
    private transient NavigableMap<E, Object> m;
    private static final Object PRESENT = new Object();

    ... rest of the code
}

Java TreeSet Methods:

MethodsDescription
boolean add(E e)It adds the specified element
E ceiling(E e)It returns the least element in this set greater than or equal to the given element, or null if there is no such element.
Iterator descendingIterator()It iterates the elements in descending order.
Iterator iterator()It iterates the elements in ascending order.
E floor(E e)It returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
E lower(E e)It returns the greatest element in this set strictly less than the given element, or null if there is no such element.
E higher(E e)It returns the least element in this set strictly greater than the given element, or null if there is no such element.
NavigableSet descendingSet()It returns the elements in reverse order.
E pollFirst()It retrieves and removes the lowest(first) element.
E pollLast()It retrieves and removes the highest(last) element.
boolean contains(Object o)It returns true if this set contains the specified element.
boolean isEmpty()It returns true if this set contains no elements.
boolean remove(Object o)It is used to remove the specified element.
void clear()It is used to remove all of the elements from this set.
Object clone()It returns a shallow copy of this TreeSet instance.
E first()It returns the first (lowest) element currently in this sorted set.
E last()It returns the last (highest) element currently in this sorted set.
int size()It returns the number of elements in this set.

Java TreeSet Example

Let’s see a simple example of TreeSet.

public class TreeSetDemo {
    // Main Method
    public static void main(String[] args) {
        TreeSet<String> treeSet = new TreeSet();
        // Adding element to TreeSet
        treeSet.add("Apple");
        treeSet.add("Banana");
        treeSet.add("Mango");
        treeSet.add("Grapes");

        System.out.println("Printing Fruits: " + treeSet);

        System.out.println("First Element: " + treeSet.first());

        System.out.println("Last Element: " + treeSet.last());

    }
}

Output:

Printing Fruits: [Apple, Banana, Grapes, Mango]
First Element: Apple
Last Element: Mango

Note: TreeSet is non synchronized. Meaning, if you’re working in a multi-threaded environment then TreeSet will not be the best fit. Instead, you’ve to use some thread-safe hashmap based collection or synchronize TreeSet externally.

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

Official Docs: Read Here