Java treeset

Hey guys!! Welcome to flower brackets blog. Today we are going to learn java treeset.

Treeset underlying data structure is Balanced Tree. In Treeset, order of elements is maintained by Set using natural ordering even if explicit comparator is provided.

Duplicate elements are not allowed hence contain only unique elements. Order of insert is not preserved but elements are sorted by “key”.

Similar kind of objects are allowed. Runtime exception “ClassCastException” is thrown if different objects are inserted. Only once “null” insertion is allowed.

Treeset objects are sorted in ascending order. Treeset implements SortedSet interface.

If you want to store large datasets with faster access and retrieval time use Treeset.

While insertion, if “null” element is added to TreeSet, “NullPointerException” is thrown. Because “null” cannot be compared with any value in TreeSet.

Operations like add, remove and search take O(log n) time and for sorting elements it takes O(n) time.


Here you can see treeset hierarchy,

java treeset

As you can see treeset class implements navigableset interface. Navigableset interface extends sortedset interface. Sortedset interface extends set interface.

Set interface extends collection interface. Collection interface extends iterable interface.

Syntax

java.util

Class TreeSet<E>
java.lang.Object
     →java.util.AbstractCollection<E>
          →java.util.AbstractSet<E>
                →java.util.TreeSet<E>

Parameters -
E - type of elements maintained by this set

Implemented Interfaces -
Serializable, Cloneable, Iterable<E>, Collection<E>, NaviagableSet<E>, Set<E>, SortedSet<E>

Treeset class belongs to java.util package. Above you can see “E” this is nothing but type of elements which we are going to store in the treeset.

Also read – sort hashmap by value

Treeset class extends abstractset class. Abstractset class extends abstractcollection class. Abstractcollection class extends object class.

Treeset class implements serializable, cloneable, iterable, collection, navigableset, set and sortedset interface.

Methods supported by treeset

MethodDescription
void add(Object o)method will add specified element according to some sorting order in TreeSet. Duplicate entries will not get added.
boolean addAll( Collection C)this method adds all the elements in the specified collection to this set. Elements in Collection should be homogeneous otherwise ClassCastException will be thrown. Duplicate Entries of Collection will not be added to TreeSet.
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.
Object clone( )returns a shallow copy of this treeset instance, which is just a simple copied set.
Object first()method will return first element in TreeSet If TreeSet is not null, else it will throw NoSuchElementException.
boolean contains( Object o )returns true if this set contains the specified element in TreeSet else it will return false.
Object last()method will return last element in TreeSet if TreeSet is not null, else it will throw NoSuchElementException.
SortedSet headSet(Object toElement)method will return elements of TreeSet which are less than the specified element.
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 comparator()method will return Comparator used to sort elements in TreeSet or it will return null if default natural sorting order is used.
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 or is empty and false for the opposite case.
Iterator 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 size of the set or the number of elements present in the set.
NavigableSet 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 subSet( Object fromElement, Object toElement )returns elements ranging from fromElement to toElement. fromElement is inclusive and toElement is exclusive.
SortedSet tailSet( Object fromElement )returns elements of TreeSet which are greater than or equal to the specified element.
NavigableSet 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 constructor

Below is the first treeset constructor,

TreeSet t = new TreeSet();

Using above constructor we can create empty new TreeSet. Treeset will order the elements in natural sorting order or ascending order by default.

Also read – HashSet java

The second treeset constructor is as shown below,

TreeSet t = new TreeSet(Comparator comp);

Above treeset constructor accepts a comparator. This constructor is used when external specification of sorting order is needed.

Third treeset constructor is as below,

TreeSet t = new TreeSet(Collection col);

This constructor accepts collection. Used when conversion is needed from Collection object to TreeSet object.

Also read – ArrayList java

And, last but not the least fourth treeset constructor is as below,

TreeSet t = new TreeSet(SortedSet s);

This constructor accepts SortedSet. Used to convert SortedSet object to TreeSet object.


Below are the methods inherited from

Methods inherited from class java.util.AbstractSet
equals, hashCode, removeAll

Methods inherited from class java.util.AbstractCollection
containsAll, retainAll, toArray, toArray, toString

Methods inherited from class java.lang.Object
wait, wait, wait, finalize, getClass, notify, notifyAll

Methods inherited from interface java.util.Set
removeAll, containsAll, hashCode, equals, retainAll, toArray, toArray


Here’s java program on treeset,

import java.util.SortedSet;
import java.util.TreeSet;

public class TreesetExample 
{
   public static void main(String[] args) 
   {
      SortedSet<String> players = new TreeSet<>();

      // adding new elements
      players.add("Bhuvaneshvar");
      players.add("Ajinkya");
      players.add("Piyush");
      players.add("Ojha");

      System.out.println("Players : " + players);

      // duplicate elements are neglected
      players.add("Ajinkya");
      System.out.println("After adding duplicate element - Ajinkya : " + players);

      // allowed because it is in lowercase
      players.add("bhuvaneshvar");
      System.out.println("After adding - bhuvaneshvar : " + players);
   }
}

Output:

Players : [Ajinkya, Bhuvaneshvar, Ojha, Piyush]
After adding duplicate element – Ajinkya : [Ajinkya, Bhuvaneshvar, Ojha, Piyush]
After adding – bhuvaneshvar : [Ajinkya, Bhuvaneshvar, Ojha, Piyush, bhuvaneshvar]


Reference – Oracle help centre

Related Posts