Java Treeset

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

Introduction : java treeset

Here you can see treeset hierarchy,

java treeset

As you can see in the above image, 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.


What is treeset?

Treeset is a collection which is used to store objects or elements. It does not contain duplicate elements.

It will contain only unique elements. Treeset maintains ascending order by default. Treeset is not synchronised and treeset class won’t allow null elements.

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

Here I will cover treeset constructor. Below is the first treeset constructor,

public TreeSet()    // default constructor

Using above constructor we can create empty new TreeSet. Once we create empty TreeSet we can add elements to the TreeSet.

Also Read – HashSet Java

Whatever elements we are adding in the treeset should implement comparable interface and treeset will order the elements in ascending order by default.

The second treeset constructor is as shown below,

public TreeSet(Comparator<? super E> comparator)

Above treeset constructor accepts a comparator. Using this constructor we can create empty treeset.

Once we create empty treeset we can add elements to the treeset. These elements will be sorted according to the comparator which we pass to the treeset constructor.

Third treeset constructor is as below,

public TreeSet(Collection<? extends E> c)

This (above) constructor accepts collection. Collection can be arraylists, set or linkedlists. Suppose say I have a collection which has three elements.

Also Read – ArrayList Java

If I pass collection to treeset constructor, above treeset constructor will create a new treeset which will contain all elements from the collection and also the elements will be ordered in ascending order.

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

public TreeSet(SortedSet<E> s)

which accepts SortedSet. SortedSet can be a treeset.

For example, say, we have a sortedset which has three elements and if we pass sortedset to treeset, above treeset constructor will create new treeset and new treeset will contain all elements from the sortedset and elements order will be same as the sortedset order.


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


Java treeset example

Here’s a simple program on treeset in java example,

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

public class TreesetExample 
{
   public static void main(String[] args) 
   {
      // here we are creating a treeset
      SortedSet<String> ts = new TreeSet<>();

      // add new elements to treeset
      ts.add("Dhoni");
      ts.add("Virat");
      ts.add("Sachin");
      ts.add("Rohit");

      System.out.println("Treeset java : " + ts + "\n");

      // here duplicate elements are ignored
      ts.add("Sachin");
      System.out.println("After adding duplicate element - Sachin : " + ts + "\n");

      // below string will be allowed because it is in lowercase.
      ts.add("rohit");
      System.out.println("After adding string - rohit : " + ts);
   }
}

Output:

Treeset java : [Dhoni, Rohit, Sachin, Virat]

After adding duplicate element - Sachin : [Dhoni, Rohit, Sachin, Virat]

After adding string - rohit : [Dhoni, Rohit, Sachin, Virat, rohit]


Treeset custom comparator – case insensitive order

Java treeset comparator (custom comparator java) example sorts elements by ignoring case. Java treeset comparator example imports comparator java.

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

public class CaseInsensitiveTreeset 
{
   public static void main(String[] args) 
   {
      SortedSet<String> players = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
      // here we are adding new elements to a treeset
      players.add("Dhoni");
      players.add("Virat");
      players.add("Sachin");
      players.add("Rohit");

      System.out.println("Treeset comparator example : " + players + "\n");

      // here we are adding lowercase string
      // and it will be considered as duplicates
      players.add("sachin");
      System.out.println("After adding string - sachin : " + players);
   }
}

Output :

Treeset comparator example : [Dhoni, Rohit, Sachin, Virat]

After adding string - sachin : [Dhoni, Rohit, Sachin, Virat]


Custom comparator – java descending order

Let’s learn java treeset comparator example which sorts elements in descending order,

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

public class DescendingOrderTreeset 
{
   public static void main(String[] args) 
   {
      SortedSet<String> colors = new TreeSet<>(Comparator.reverseOrder());
      // here we are adding new elements to a treeset
      colors.add("Blue");
      colors.add("Aqua");
      colors.add("Pink");
      colors.add("Red");

      System.out.println("Treeset comparator example : " + colors + "\n");
   }
}

Output :

Treeset comparator example : [Red, Pink, Blue, Aqua]


How to access elements of a treeset?

Below are few methods with sample java programs to access elements of a treeset,

// size method example

import java.util.TreeSet;

public class TreesetSizeDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> tsNum = new TreeSet<Integer>();
      tsNum.add(22);
      tsNum.add(24);
      tsNum.add(26);
      tsNum.add(28);
      tsNum.add(30);

      System.out.println("Treeset java example : " + tsNum + "\n");

      // here it returns number of elements in this set
      int size = tsNum.size();

      System.out.println("Treeset java size : " + size);
   }
}

Output :

Treeset java example : [22, 24, 26, 28, 30]

Treeset java size : 5


Let’s see how to check particular element is present or not using sample program,

// Treeset contains(Object o) method example

import java.util.TreeSet;

public class TreesetContainsDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(22);
      ts.add(24);
      ts.add(26);
      ts.add(28);
      ts.add(30);

      System.out.println("Treeset java example : " + ts + "\n");

      // this method returns true if above treeset contains the specified element
      boolean checkNum = ts.contains(24);
      System.out.println("Treeset java contains(Object o) method example : " + checkNum);
   }
}

Output :

Treeset java example : [22, 24, 26, 28, 30]

Treeset java contains(Object o) method example : true


// Treeset first() method example

import java.util.TreeSet;

public class TreesetFirstDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(33);
      ts.add(44);
      ts.add(11);
      ts.add(55);
      ts.add(22);

      System.out.println("Treeset java example : " + ts + "\n");
      // first() method returns lowest element in treeset
      Integer num = ts.first();
      System.out.println("Treeset java first() method example : " + num);
   }
}

Output :

Treeset java example : [11, 22, 33, 44, 55]

Treeset java first() method example : 11


// Treeset last() method example

import java.util.TreeSet;

public class TreestLastDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(33);
      ts.add(44);
      ts.add(11);
      ts.add(55);
      ts.add(22);

      System.out.println("Treeset java example : " + ts + "\n");
      // last() method returns highest element in treeset
      Integer num = ts.last();
      System.out.println("Treeset java last() method example : " + num);
   }
}

Output :

Treeset java example : [11, 22, 33, 44, 55]

Treeset java last() method example : 55


// Treeset higher(E e) method example

import java.util.TreeSet;

public class TreesetHigherDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> tsNumber = new TreeSet<Integer>();
      tsNumber.add(33);
      tsNumber.add(44);
      tsNumber.add(11);
      tsNumber.add(55);
      tsNumber.add(22);

      System.out.println("Treeset java example : " + tsNumber + "\n");

      // higher(E e) method returns least element in above treeset
      // greater than the given element or null if no such element

      Integer num = tsNumber.higher(34);
      System.out.println("Treeset java higher() method example : " + num + "\n");

      num = tsNumber.higher(56);
      System.out.println("Treeset java higher() method example : " + num);
   }
}

Output :

Treeset java example : [11, 22, 33, 44, 55]

Treeset java higher() method example : 44

Treeset java higher() method example : null


// Treeset lower(E e) method example

import java.util.TreeSet;

public class TreesetLowerDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> tsNumber = new TreeSet<Integer>();
      tsNumber.add(33);
      tsNumber.add(44);
      tsNumber.add(11);
      tsNumber.add(55);
      tsNumber.add(22);

      System.out.println("Treeset java example : " + tsNumber + "\n");

      // lower() method returns greatest element in above treeset 
      // less than the given element or null if no such element

      Integer num = tsNumber.lower(34);
      System.out.println("Treeset java lower() method example : " + num + "\n");

      num = tsNumber.lower(56);
      System.out.println("Treeset java lower() method example : " + num);
   }
}

Output :

Treeset java example : [11, 22, 33, 44, 55]

Treeset java lower() method example : 33

Treeset java lower() method example : 55


// Treeset toArray(T[] a) method example

import java.util.TreeSet;

public class TreesetToArrayDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> tsNumber = new TreeSet<Integer>();
      tsNumber.add(33);
      tsNumber.add(44);
      tsNumber.add(11);
      tsNumber.add(55);
      tsNumber.add(22);

      System.out.println("Treeset java example : " + tsNumber + "\n");

      // in this method treeset elements will be copied to integer array

      Integer arr[] = new Integer[tsNumber.size()];
      tsNumber.toArray(arr);
      for(Integer num : arr)
      {
         System.out.println(num);
      }
   }
}

Output :

Treeset java example : [11, 22, 33, 44, 55]

11
22
33
44
55


How to remove elements from treeset?

Here we will learn how to remove element from treeset. Let’s see few methods to remove elements from treeset,

// Treeset remove(Object o) method example

import java.util.TreeSet;

public class TreesetRemoveDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> num = new TreeSet<Integer>();
      num.add(33);
      num.add(44);
      num.add(11);
      num.add(55);
      num.add(22);

      System.out.println("Treeset java example : " + num + "\n");

      // remove(Object o) method removes specified element 
      // from above treeset if it is present

      boolean checkRemove = num.remove(11);
      System.out.println("Treeset java remove(Object o) method example : " + checkRemove + "\n");
      System.out.println("New Treeset : " + num + "\n");
   }
}

Output :

Treeset java example : [11, 22, 33, 44, 55]

Treeset java remove(Object o) method example : true

New Treeset : [22, 33, 44, 55]


// Treeset removeAll(Collection<? extends E> c) method example

import java.util.LinkedList;
import java.util.TreeSet;

public class TreesetRemoveAllDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(32);
      ts.add(42);
      ts.add(200);
      ts.add(400);
      ts.add(22);

      System.out.println("Treeset java example : " + ts + "\n");

      LinkedList<Integer> li = new LinkedList<Integer>();
      li.add(200);
      li.add(400);

      System.out.println("LinkedList : " + li + "\n");

      // remove all method removes all elements from the above
      // set that are contained in the specified condition

      boolean checkRemove = ts.removeAll(li);
      System.out.println("Treeset java removeAll(Collection<? extends E> c) method example : " + checkRemove + "\n");
      System.out.println("New Treeset : " + ts);
   }
}

Output :

Treeset java example : [22, 32, 42, 200, 400]

LinkedList : [200, 400]

Treeset java removeAll(Collection<? extends E> c) method example : true

New Treeset : [22, 32, 42]


// Treeset pollFirst() method example

import java.util.TreeSet;

public class TreesetPollFirstDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(32);
      ts.add(42);
      ts.add(12);
      ts.add(52);
      ts.add(22);

      System.out.println("Treeset java example : " + ts + "\n");

      // pollFirst() method retrieves and removes lowest element
      // or first element or returns null if set is empty

      Integer num = ts.pollFirst();
      System.out.println("Treeset pollFirst() method example : " + num + "\n");
      System.out.println("New Treeset : " + ts + "\n");
   }
}

Output :

Treeset java example : [12, 22, 32, 42, 52]

Treeset pollFirst() method example : 12

New Treeset : [22, 32, 42, 52]


// Treeset pollLast() method example

import java.util.TreeSet;

public class TreesetPollLastDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(32);
      ts.add(42);
      ts.add(12);
      ts.add(52);
      ts.add(22);

      System.out.println("Treeset java example : " + ts + "\n");

      // pollLast() method retrieves and removes the last (highest)
      // element or returns null if set is empty

      Integer num = ts.pollLast();
      System.out.println("Treeset pollLast() method example : " + num + "\n");
      System.out.println("New Treeset : " + ts + "\n");
   }
}

Output :

Treeset java example : [12, 22, 32, 42, 52]

Treeset pollLast() method example : 52

New Treeset : [12, 22, 32, 42]


// Treeset clone() method example

import java.util.TreeSet;

public class TreesetCloneDemo 
{
   public static void main(String[] args) 
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(32);
      ts.add(42);
      ts.add(12);
      ts.add(52);
      ts.add(22);

      System.out.println("Treeset java example : " + ts + "\n");

      // clone() method returns shallow copy of above treeset
      // instance (elements themselves are not cloned).

      TreeSet<String> copy = (TreeSet<String>) ts.clone();
      System.out.println("Treeset clone() method example : " + copy);
   }
}

Output :

Treeset java example : [12, 22, 32, 42, 52]

Treeset clone() method example : [12, 22, 32, 42, 52]


Treeset – user defined object

Here we are going to learn to create treeset of user defined objects. Basically treeset sorts elements in ascending order.

So either the class should implement Comparable interface and provide implementation for compareTo() function or

We must provide custom comparator while creating treeset. Here treeset uses compareTo() method to compare two elements and sort them.

// Student class

import java.util.Objects;

public class Student implements Comparable<Student> 
{
   private int ID;
   private String name;

   public Student(int ID, String name)
   {
      this.ID = ID;
      this.name = name;
   }

   public int getId() 
   {
      return ID;
   }

   public void setId(int ID) 
   {
      this.ID = ID;
   }

   public String getName() 
   {
      return name;
   }

   public void setName(String name) 
   {
      this.name = name;
   }

   // here two Students are equal if their IDs are equal
   @Override
   public boolean equals(Object o) 
   {
      if(this == o) return true;
      if(o == null || getClass() != o.getClass()) return false;
      Student student = (Student) o;
      return ID == student.ID;
   }

   @Override
   public int hashCode() 
   {
      return Objects.hash(ID);
   }

   // compare students based on their IDs
   @Override
   public int compareTo(Student student) 
   {
      return this.getId() - student.getId();
   }

   @Override
   public String toString() 
   {
      return "Student { " + " ID = " + ID + ", name = '" + name + '\'' + '}';
   }
}

// main class

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

public class TreesetUserDefinedDemo 
{
   public static void main(String[] args) 
   {
      // here we are creating a treeset of user defined objects

      SortedSet<Student> tutee = new TreeSet<>();

      tutee.add(new Student(101, "Ronald"));
      tutee.add(new Student(102, "Scott"));
      tutee.add(new Student(103, "Charlotte"));

      System.out.println("Student's sorted based on Student class's compareTo() function) : " + tutee + "\n");

      // here we are providing a Custom Comparator
      // this comparator compares the tutees based on their name

      tutee = new TreeSet<>(Comparator.comparing(Student :: getName));

      tutee.add(new Student(101, "Ronald"));
      tutee.add(new Student(102, "Scott"));
      tutee.add(new Student(103, "Charlotte"));

      System.out.println("Student sorted based on the supplied Comparator : " + tutee); 
   }
}

Output :

Student's sorted based on Student class's compareTo() function) : [Student { ID = 101, name = 'Ronald'}, Student { ID = 102, name = 'Scott'},
Student { ID = 103, name = 'Charlotte'}]

Student sorted based on the supplied Comparator : [Student { ID = 103, name = 'Charlotte'}, Student { ID = 101, name = 'Ronald'},
Student { ID = 102, name = 'Scott'}]


Treeset iterator() method

Let’s learn how to print a treeset in java using java treeset iterator() method. Here’s example,

// public Iterator<E> iterator() method example

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

public class TreesetIteratorDemo 
{
   public static void main(String[] args) 
   {
      // here we are creating a TreeSet 
      TreeSet <Integer> ts = new TreeSet<Integer>();

      ts.add(10);
      ts.add(32);
      ts.add(27);
      ts.add(5);

      // here we are creating ascending iterator
      Iterator iterate;
      iterate = ts.iterator();

      // printing the Tree set data
      System.out.println("Treeset java iterator example in ascending order : "); 
      while(iterate.hasNext())
      {
         System.out.println(iterate.next() + " ");
      }
   }
}

Output :

Treeset java iterator example in ascending order :
5
10
27
32


conclusion

So this is about treeset java collection framework. I hope you have understood the concept.

You can subscribe to my blog flower brackets if you haven’t already.


Reference – Oracle help centre

You May Also Like