Java TreeSet tutorial

Java TreeSet class is the most significant execution in Java’s collection framework.

  • It extends the SortedSet interface and implements the Navigable Set interface.
  • It provides the service to store data in a tree-like data structure.

Java TreeSet

Java Tree Set

Some key features of the TreeSet in Java:

  • TreeSet cannot contain duplicate elements.
  • It is not thread-safe.
  • It doesn’t permit the null element.
  • It sorts the elements in ascending order.
  • It internally uses a TreeMap to store the elements.

Before creating a tree set, we must import a package i.e. java.util.TreeSet.

After importing the package, we create TreeSet like this,

TreeSet<String> student = new TreeSet<>();

//or can create as below to store integer values,

TreeSet<Integer> number= new TreeSet<>();

 

Let’s see some methods of TreeSet :

1. Insert(), remove(), iterator(), and descendingIterator() methods of Java TreeSet :

  • add() : adding specified elements to TreeSet.
  • remove() : expelling specified elements from TreeSet.
  • Iterator() : Traversing elements of TreeSet.
  • descendingIterator() : Traversing elements of TreeSet in descending order.
import java.util.*;

class TreeSetExample1{

  public static void main(String ar[])
  {
    TreeSet<Integer> num= new TreeSet<Integer>();
  
    //add() method 
    num.add(3);
    num.add(5);
    num.add(2);
    num.add(8);
    num.add(6);
      
    //TreeSet of Integer type
    System.out.println("Integer TreeSet : "+num);

    num.add(2);

    System.out.println("After adding duplicate element 2 : "+num);


    //remove() method
    num.remove(5);

    System.out.println("After removing 5 from TreeSet : "+num);


    //iterate() method
    Iterator<Integer> itr1= num.iterator();
    System.out.println("Accessing elements using Iterator method : ");
    while(itr1.hasNext())
    {
      System.out.println(itr1.next());
    }	


    //descendingIterator() method
    Iterator<Integer> itr2= num.descendingIterator();
    System.out.println("Accessing elements in descending order : ");
    while(itr2.hasNext())
    {
      System.out.println(itr2.next());
    }
  }
}

output :

num TreeSet : [2, 3, 5, 6, 8]
After adding duplicate element 2 : [2, 3, 5, 6, 8]
After removing 5 from TreeSet : [2, 3, 6, 8]
Accessing elements using Iterator method :
2
3
6
8
Accessing elements in descending order :
8
6
3
2

2. first(), last(), higher(), and lower() methods of TreeSet :

  • first() : Returns the first element of the TreeSet.
  • last() : Returns the last component of the TreeSet.
  • higher() : Returns element just greater than the specified element from the TreeSet.
  • lower() : Returns element just lower than the specified element from the TreeSet.
import java.util.*;

class TreeSetExample2{

  public static void main(String ar[])
  {
    TreeSet<Integer> num= new TreeSet<Integer>();
  
    num.add(3);
    num.add(5);
    num.add(2);
    num.add(8);
    num.add(6);
      
    System.out.println("Integer TreeSet : "+num);
    
    //first() method
    int firstNum= num.first();
    System.out.println("first number of TreeSet : "+firstNum);


    //last() method
    int lastNum= num.last();
    System.out.println("last number of TreeSet : "+lastNum);


    //higher() method
    int higherNum= num.higher(5);
    System.out.println("just higher number than 5 from TreeSet : "+higherNum);

  
    //lower() method
    int lowerNum= num.lower(5);
    System.out.println("just lower element than 5 from TreeSet : "+lowerNum); 
  }
}

output :

Integer TreeSet : [2, 3, 5, 6, 8]
first number of TreeSet : 2
last number of TreeSet : 8
just higher number than 5 from TreeSet : 6
just lower element than 5 from TreeSet : 3

 

3. headSet(), tailSet(), subSet(), and descendingSet() methods of TreeSet :

  • headSet() : Returns all elements of TreeSet whose value not more than the specified element.
  • tailSet() : Returns all elements of TreeSet whose values are higher than or equal to the specified element.
  • subSet() : Returns all elements ranging from e1 element to e2 element. where e1 element is inclusive and e2 element is exclusive.
  • descendingSet() : Returns all elements of TreeSet in descending order.
import java.util.*;

class TreeSetExample3{

  public static void main(String ar[])
  {
    TreeSet<Integer> num= new TreeSet<Integer>();
  
    num.add(3);
    num.add(5);
    num.add(2);
    num.add(8);
    num.add(6);
      
    System.out.println("Integer TreeSet : "+num);

    //headSet() method : 
    
    //SortedSet operation
    System.out.println("headSet method without boolean value : "+num.headSet(5));

    //NavigableSet Operation
    System.out.println("headSet method with boolean value : "+num.headSet(5, true));


    //tailSet() method : 

    //SortedSet operation
    System.out.println("tailSet method without boolean value : "+num.tailSet(5));	

    //NavigableSet Operation
    System.out.println("tailSet method with boolean value : "+num.tailSet(5, false));	


    //subSet() method : 

    //SortedSet operation
    System.out.println("subSet method without boolean value : "+num.subSet(3, 6));

    //NavigableSet Operation
    System.out.println("subSet method with boolean value : "+num.subSet(3, false, 6, true));


    //descendingSet() method
    System.out.println("TreeSet elements in descending order : "+num.descendingSet());
  }
}

output :

Integer TreeSet : [2, 3, 5, 6, 8]
headSet method without boolean value : [2, 3]
headSet method with boolean value : [2, 3, 5]
tailSet method without boolean value : [5, 6, 8]
tailSet method with boolean value : [6, 8]
subSet method without boolean value : [3, 5]
subSet method with boolean value : [5, 6]
TreeSet elements in descending order : [8, 6, 5, 3, 2]

 

4. contains(), isEmpty(), size(), and clear() methods of TreeSet :

  • contains() : Check whether a specified element is present in a given TreeSet.
  • isEmpty() : Identify if the given TreeSet is empty or not.
  • size() : Returns the total number of components present in the TreeSet.
  • clear() : Removes all the components present in the TreeSet.
import java.util.*;

class TreeSetExample4{

  public static void main(String ar[])
  {
    TreeSet<Integer> num= new TreeSet<Integer>();
  
    num.add(3);
    num.add(5);
    num.add(2);
    num.add(8);
    num.add(6);
      
    System.out.println("Integer TreeSet : "+num);


    //contains() method
    System.out.println("Is TreeSet contain 6 : "+num.contains(6));


    //isEmpty() method
    System.out.println("Is TreeSet empty : "+num.isEmpty());		


    //size() method
    System.out.println("size of TreeSet : "+num.size());


    //clear() method
    num.clear();
    System.out.println("After clear() method, Integer TreeSet = "+num);	

  }
}

output :

Integer TreeSet : [2, 3, 5, 6, 8]
Is TreeSet contain 6 : true
Is TreeSet empty : false
size of TreeSet : 5
After clear() method, Integer TreeSet = []

 

5. Storing Null elements :

Elements sorted according to their natural order in Set as like as we add a new element to a TreeSet. If we add null to the TreeSet, it results in a NullPointerException because it first compares to all other elements present in Set before it adds to Set. Since null cannot be compared to any other value, it shows an exception.

import java.util.*;

class TreeSetExample5{

  public static void main(String ar[])
  {

    try
    {
      TreeSet<Integer> num= new TreeSet<Integer>();
    
      num.add(3);
      num.add(5);
      num.add(2);
      num.add(8);
      num.add(6);
        
      System.out.println("Integer TreeSet : "+num);

      
      //adding null to Set
      num.add(null);

    }catch(Exception e)
    {
      System.out.println("Exception : "+e);
    }
  }
}

output :

Integer TreeSet : [2, 3, 5, 6, 8]
Exception : java.lang.NullPointerException

 

6. Tree Set with User Defined Objects :

To create user-defined objects in TreeSet, we need to implement our class with a comparable interface to keep class objects sorted. We also need to provide the implementation of compareTo() function in the class.

import java.util.*;

class Student implements Comparable<Student>
{
  int rollno;
  String name;

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

  public int compareTo(Student s)
  {
    if(rollno > s.rollno)
      return 1;
    else if(rollno < s.rollno)
      return -1;
    else 
      return 0;
  }
}


class TreeSetExample6{

  public static void main(String ar[])
  {

    Set<Student> stu= new TreeSet<Student>();

    Student s1= new Student(7, "Rohan");
    Student s2= new Student(20, "Sam");
    Student s3= new Student(45, "Alexander");
    Student s4= new Student(25, "John");
    Student s5= new Student(5, "Jack");
  
    stu.add(s1);
    stu.add(s2);
    stu.add(s3);
    stu.add(s4);
    stu.add(s5);

  		//Traversing all elements of TreeSet
    for(Student st : stu)
    {
      System.out.println("Student Roll no. : "+st.rollno+" ,	 name : "+st.name);
    }
  }
}

output :

Student Roll no. : 5 , name : Jack
Student Roll no. : 7 , name : Rohan
Student Roll no. : 20 , name : Sam
Student Roll no. : 25 , name : John
Student Roll no. : 45 , name : Alexander

 

Also, go through another tutorial:

How to validate identifier using Regular Expression in Java

Singleton Design Pattern in Java

Leave a Reply

Your email address will not be published. Required fields are marked *