TreeSet in Java with Example – Methods, Constructors, Operations | How TreeSet Works Internally in Java?

Treeset internal implementation in java: TreeSet in Java is an implementation class of the SortedSet interface that uses a tree for storage. Java TreeSet is the most important part of the collection framework. TreeSet class in Java came in Java 1.2 version. In Java TreeSet objects are stored in sorted and ascending order, therefore, access and retrieval time are quite fast, which makes TreeSet is the best choice when storing a large amount of sorted information that must be found very quickly.

Hierarchy of TreeSet Class

TreeSet in Java with Example 1

The important points about TreeSet in Java:

  1. The underlying data structure for TreeSet is Tree.
  2. Java TreeSet doesn’t allow you to store duplicates elements.
  3. In Java TreeSet insertion order is not preserved.
  4. Java TreeSet doesn’t allow you to store heterogeneous objects, it will give you ClassCastException if you are trying to insert heterogeneous elements.
  5. If you are depending on the default natural sorting order then objects should be homogeneous and comparable. If the objects are not comparable and homogeneous then it will give you a runtime exception.
  6. Java TreeSet allows you to insert the null element but only once till Java 6 version.
  7. Java TreeSet is the best choice for storing large amounts of sorted information.

Constructors in Java TreeSet

Java treeset example: There are 4 constructors are defined in Java TreeSet, which are described below

Constructor Description
TreeSet() The first constructor creates an empty tree set where elements are sorted in ascending order according to the default natural sorting order.
TreeSet(Comparator comp) The second constructor creates an empty tree set where elements will be inserted according to the customized sorting order using a comparator object.
TreeSet(Collection c) The third constructor creates a tree set that contains the elements of collection c.
TreeSet(SortedSet ss) The fourth constructor creates a tree set that contains the elements of SortedSet ss.

Treeset Methods in Java

Java TreeSet defines all the methods which are available in NavigableSet, SortedSet, and collection interface. Some of them are discussed below:

Method Description
void add(Object obj) This method is used to add the elements in TreeSet according to some sorting order.
Object first() This method returns the first element from TreeSet if TreeSet is not null else it will give you a runtime exception NoSuchElementException.
Object last() This method returns the last element from TreeSet if TreeSet is not null else it will give you a runtime exception NoSuchElementException.
boolean contains(Object obj) This method returns true if TrreeSet contains the specified object else it returns false.
void clear() This method is used to remove all the elements from TreeSet.
int size() This method is used to return the size of the set.
boolean remove(Object obj) This method is used to remove the specified element from TreeSet.
boolean isEmpty() This method returns true if the set contains no elements.
Object clone() This method returns the shallow copy of the TreeSet instance.

Operations on TreeSet Class

Let us discuss in detail the various commonly performed operations on TreeSet

Adding Elements

To add elements to the TreeMap we use the add() method. However, Treeset will not retain the Insertion Order. Internally for each and every element, the values are compared and then sorted in ascending order. Remember duplicate elements aren’t allowed and duplicate elements are ignored. Null Values aren’t accepted by the TreeSet.

// Java code to demonstrate
// the working of TreeSet
import java.util.*;

class TreeSetDemo {

public static void main(String[] args)
{
Set<String> ts = new TreeSet<>();

// Elements are added using add() method
ts.add("Geek");
ts.add("For");
ts.add("Geeks");

System.out.println(ts);
}
}

Output:

[For, Geek, Geeks]

Accessing the Elements

After adding the elements if you want to access the elements you can use the inbuilt methods such as contains(), first(), last(), etc.

// Java code to demonstrate the workings of TreeSet
import java.util.*;
class TreeSetDemo {

public static void main(String[] args)
{
NavigableSet<String> ts = new TreeSet<>();

// Elements are added using add() method
ts.add("Geek");
ts.add("For");
ts.add("Geeks");

System.out.println("Tree Set is " + ts);

String check = "Geeks";

// Check if the above string exists in
// the treeset or not
System.out.println("Contains " + check + " "
+ ts.contains(check));

// Print the first element in
// the TreeSet
System.out.println("First Value " + ts.first());

// Print the last element in
// the TreeSet
System.out.println("Last Value " + ts.last());

String val = "Geek";

// Find the values just greater
// and smaller than the above string
System.out.println("Higher " + ts.higher(val));
System.out.println("Lower " + ts.lower(val));
}
}

Output:

Tree Set is [For, Geek, Geeks]
Contains Geeks true
First Value For
Last Value Geeks
Higher Geeks
Lower For

Removing Values

We can remove the values from the TreeSet using the method remove(). There are several methods to use in order to remove the first or last value.

// Java code to demonstrate
// the working of TreeSet

import java.util.*;
class TreeSetDemo {

public static void main(String[] args)
{
NavigableSet<String> ts = new TreeSet<>();

// Elements are added using add() method
ts.add("Geek");
ts.add("For");
ts.add("Geeks");
ts.add("A");
ts.add("B");
ts.add("Z");

System.out.println("Initial TreeSet " + ts);

// Removing the element b
ts.remove("B");

System.out.println("After removing element " + ts);

// Removing the first element
ts.pollFirst();

System.out.println("After removing first " + ts);

// Removing the last element
ts.pollLast();

System.out.println("After removing last " + ts);
}
}

Output:

Initial TreeSet [A, B, For, Geek, Geeks, Z]
After removing element [A, For, Geek, Geeks, Z]
After removing first [For, Geek, Geeks, Z]
After removing last [For, Geek, Geeks]

Iterating through the TreeSet

There are a number of ways to iterate through the Treeset. Of all those one of the popular methods is to use the enhanced for loop.

// Java code to demonstrate
// the working of TreeSet

import java.util.*;
class TreeSetDemo {

public static void main(String[] args)
{
Set<String> ts = new TreeSet<>();

// Elements are added using add() method
ts.add("Geek");
ts.add("For");
ts.add("Geeks");
ts.add("A");
ts.add("B");
ts.add("Z");

// Iterating though the TreeSet
for (String value : ts)
System.out.print(value + ", ");
System.out.println();
}
}

Output:

A, B, For, Geek, Geeks, Z,

Features of a TreeSet

  • Treeset Implements Sorted Interface. Thus, duplicate values are not permissible.
  • TreeSet Objects are stored in a sorted and ascending order.
  • It doesn’t preserve the insertion order of elements. However, elements are sorted by keys.
  • If we depend on the default natural sorting order then the object being inserted into the tree needs to be homogeneous and comparable.
  • Treeset doesn’t allow heterogeneous object insertion. If we try to add heterogeneous objects it will throw a classCastException during the Runtime.
  • It accepts only generic types that are comparable.

Also, Read:

How Treeset Works Internally in Java?

Treeset is an implementation of the self-balancing binary search tree. Thus operations such as add, remove, and search takes O(log(N)) time. It is because in a self-balancing tree the height is always made sure that O(log(N)) for all kinds of Operations. Thus, Treeset is considered to be an almost efficient data structure in order to store huge sorted data as well as perform operations on it. Operations such as Printing N elements in the sorted order take O(N) time.

Synchronized TreeSet: Treeset Implementation isn’t synchronized. It means if multiple threads access a set concurrently then at least one of the threads modifies the set and it must be synchronized externally. This is obtained by synchronizing some objects that naturally encapsulate the set. If there are no such objects then the set needs to be wrapped using the Collections.synchronizedSortedSet Method. It is done at the time of creation so as to prevent accidental unsynchronized access to the set.

TreeSet ts = new TreeSet(); 
Set syncSet = Collections.synchronziedSet(ts);

TreeSet in Java with Example

import java.util.*;
class Person
{
public static void main(String args[])
{

//creating a tree set
TreeSet tset = new TreeSet();

//adding elements in the tree set
tset.add("Ajay");
tset.add("Vijay");
tset.add("Amit");
tset.add("Sumit");
tset.add("Rahul");

//displaying elements
System.out.println("The tree set elements are: " +tset);
}
}

Output:

TreeSet in Java with Example 2

Java TreeSet Example to Add a Heterogeneous Element

Java TreeSet doesn’t allow you to store heterogeneous objects, it will give you ClassCastException if you are trying to insert heterogeneous elements.

import java.util.*;
class Person
{
public static void main(String args[])
{
//creating a tree set
TreeSet tset = new TreeSet();

//adding elements in the tree set
tset.add("Ajay");
tset.add("Vijay");
tset.add("Amit");
tset.add("Sumit");
tset.add("Rahul");

//add heterogenos element
tset.add(new Integer(10));

//displaying elements
System.out.println("The tree set elements are: " +tset);
}
}

Output:

TreeSet in Java with Example 3

Java TreeSet Example to Insert a Null Element in the Non-Empty TreeSet

If we are trying to insert the null element as a non-empty tree set, it will give you a runtime exception because the null element compared to the existing elements, and the null value can’t be compared to any element.

import java.util.*;
class treeSetExample
{
public static void main(String args[])
{

//creating a tree set
TreeSet tset = new TreeSet();

//adding elements in the tree set
tset.add("Ajay");
tset.add("Vjay");
tset.add("Amit");
tset.add("Sumit");
tset.add("Rahul");

//add heterogenos element
tset.add(null);

//displaying elements
System.out.println("The tree set elements are: " +tset);
}
}

Output:

TreeSet in Java with Example 4

Note: Insert the new value in the tree set till all 6 versions of Java were allowed but after Java version 6 it was considered a null pointer exception.

Java TreeSet Example to Insert String Buffer Type of Elements

If we are depending on the default natural sorting order then the object should be comparable and homogeneous, An object is said to be comparable if its corresponding class implements the Comparable interface. In this example, the Ist condition is satisfied nut 2nd condition is not satisfied because the StringBuffer class does implement the Comparable interface.

import java.util.*;
class Person { public static void main(String args[]) { 
//creating a tree set TreeSet tset = new TreeSet(); 
//adding elements in the tree set 
tset.add(new StringBuffer("Ajay")); 
tset.add(new StringBuffer("Vjay")); 
tset.add(new StringBuffer("Amit")); 
tset.add(new StringBuffer("Sumit")); 
tset.add(new StringBuffer("Rahul")); 
//displaying elements 
System.out.println("The tree set elements are: " +tset); 
} 
}

Output:

TreeSet in Java with Example 5