TreeSet in Java

TreeSet provides an implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like simple set with the exception that it stores elements in sorted format.Following are the features of TreeSet.

  • TreeSet uses tree data structure for storage.
  • Objects are stored in sorted, ascending order. But we can iterate in descending order using method TreeSet.descendingIterator().
  • Access and retrieval times are very fast which make TreeSet an excellent choice for storage of large volume of data in sorted format.
  • TreeSet doesn’t use hashCode() and equals() methods to compare it’s elements. It uses compare() (or compareTo()) method to determine the equality of two elements.

Important Methods of treeset class:

  • boolean add(E e): This method adds the specified element to this set if it is not already present.
  • E ceiling(E e): This method returns the least element in this set greater than or equal to the given element, or null if there is no such element.
  • boolean contains(Object o): This method returns true if this set contains the specified element.
  • E floor(E e): This method Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
  • E pollFirst(): This method retrieves and removes the first (lowest) element, or returns null if this set is empty.
  • E pollLast(): This method retrieves and removes the last (highest) element, or returns null if this set is empty.
  • boolean remove(Object o):This method removes the specified element from this set if it is present.

The following is a very simple TreeSet implementation including TreeSet is sorting,iteration in a TreeSet, retrieving first and last elemen and remove an element.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate working TreeSet collection
import java.util.Iterator;
import java.util.TreeSet;
  
public class TreeSetExample
{
    public static void main(String[] args)
    {
        TreeSet<Integer> ts = new TreeSet<Integer>();
        ts.add(10);
        ts.add(61);
        ts.add(87);
        ts.add(39);
  
        Iterator<Integer> iterator = ts.iterator();
        System.out.print("Tree set data: ");
  
        // note that 87 being largest element, appears in
        // the last.
        while (iterator.hasNext())
            System.out.print(iterator.next() + " ");
        System.out.println();
  
        // to check if treeset is empty or not.
        if (ts.isEmpty())
            System.out.print("Tree Set is empty.");
        else
            System.out.println("Tree Set size: " + ts.size());
  
        // To get the smallest element from the set
        System.out.println("First data: " + ts.first());
  
        // To get the largest value from set
        System.out.println("Last data: " + ts.last());
  
        // remove 61 from set.
        if (ts.remove(61))
            System.out.println("Data is removed from tree set");
        else
            System.out.println("Data doesn't exist!");
  
        System.out.print("Now the tree set contain: ");
        iterator = ts.iterator();
  
        // Displaying the Tree set data
        while (iterator.hasNext())
            System.out.print(iterator.next() + " ");
  
        System.out.println();
        System.out.println("Now the size of tree set: " +
                           ts.size());
  
        // Remove all
        ts.clear();
        if (ts.isEmpty())
            System.out.print("Tree Set is empty.");
        else
            System.out.println("Tree Set size: " + ts.size());
    }
}

chevron_right


Output:

Tree set data: 10 39 61 87 
Tree Set size: 4
First data: 10
Last data: 87
Data is removed from tree set
Now the tree set contain: 10 39 87 
Now the size of tree set: 3
Tree Set is empty.

Please refer TreeSet in Java with Examples for more details.

This article is contributed by Rishabh Mahrsee. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up