TreeSet in java

Let’s learn TreeSet in java.

TreeSet in java

  • TreeSet underlying data structure is Balanced Tree.
  • TreeSet implements Serializable and Cloneable interface. But not RandomAccess interface.
  • In TreeSet duplicate objects are not allowed.
  • TreeSet does not allow to insert heterogeneous objects. Runtime exception ClassCastException is thrown, if we try to add heterogeneous objects.
  • Null insertion is possible. But only once.
  • TreeSet objects are sorted and stored in ascending order. Insertion order is not preserved.
  • All objects will be inserted based on some sorting order. It may be default natural sorting order or customized sorting order.
  • TreeSet is best choice for storing large amounts of data. It has faster retrieval and access time.

Here’s java treeset example.

import java.util.TreeSet;

public class TreeSetExamples
{
   public static void main(String[] args)
   {
      TreeSet ts = new TreeSet();
      ts.add("Ajay");
      ts.add("abhi");
      ts.add("barat");
      ts.add("zabi");
      ts.add("kiran");
      System.out.println(ts);
   }
}

Output:

[Ajay, abhi, barat, kiran, zabi]


TreeSet methods

MethodDescription
boolean add(E e)adds the specified element to this set if it is not already present.
boolean addAll(Collection<? extends E> c)adds all of the elements in the specified collection to this set.
E ceiling(E e)returns least element in this set greater than or equal to the given element or null if there is no such element.
void clear()removes all the elements form this set.
Iterator<E> descendingIterator()returns an iterator over the elements in this set in descending order.
NavigableSet<E> descendingSet()returns a reverse order view of the elements contained in this set.
Object clone()returns a shallow copy of this TreeSet instance.
boolean contains(Object o)returns true if this set contains the specified element.
SortedSet<E> headSet(E toElement)returns a view of the portion of this set whose elements are strictly less than toElement.
NavigableSet<E> headSet(E toElement, boolean inclusive)returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) toElement.
E first()returns the first (lowest) element currently in this set.
E floor(E e)returns the greatest element in this set less than or equal to the given element or null if there is no such element.
Comparator<? super E> comparator()returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
E higher(E e)returns the least element in this set strictly greater than the given element or null if there is no such element.
boolean isEmpty()returns true if this set contains no elements.
Iterator<E> iterator()returns an iterator over the elements in this set in ascending order.
E last()returns the last (highest) element currently in this set.
E lower(E e)returns the greatest element in this set strictly less than the given element or null if there is no such element.
E pollFirst()retrieves and removes the first (lowest) element or returns null if this set is empty.
E pollLast()retrieves and removes the last (highest) element or returns null if this set is empty.
boolean remove(Object o)removes the specified element from this set if it is present.
int size()returns the number of elements in this set (its cardinality).
NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)returns a view of the portion of this set whose elements range from fromElement to toElement.
SortedSet<E> subSet(E fromElement, E toElement)returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
SortedSet<E> tailSet(E fromElement)returns a view of the portion of this set whose elements are greater than or equal to fromElement.
NavigableSet<E> tailSet(E fromElement, boolean inclusive)returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.

TreeSet constructors

TreeSet t = new TreeSet();

Creates an empty TreeSet object where elements will be inserted according to default natural sorting order.


TreeSet t = new TreeSet(Comparator c);

Creates an empty treeset object where objects will be inserted according to customized sorting order described by Comparator object.


TreeSet t = new TreeSet(Collection c);

Creates an empty treeset object where we can pass any Collection object and it will create an equivalent treeset object is created.


TreeSet t = new TreeSet(SortedSet s);

For given SortedSet object we can create an equivalent treeset object.


NOTE:

  • Do not insert null value into TreeSet. Because it throws NullPointerException.
  • If we are depending on default natural sorting order compulsory the objects should be homogeneous and comparable. If not RuntimeException:ClassCastException is thrown.
  • An object is comparable only if a class implements Comparable interface.

When to use treeset in java

Let’s learn when to use treeset in java.

  • Use TreeSet when requirement is sorted unique elements. Since TreeSet elements are always in ascending order.
  • Use TreeSet if there are two entries in nearby order. Because TreeSet has higher locality which places entries close to each other in data structure and in memory.
  • Use TreeSet when you want to perform read/write operations frequently. Because treeset uses red-black tree algorithm.

Reference – Oracle help centre