×

TreeSet in Java

Java TreeSet with Example

Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not include the null element. The TreeSet class is synchronized. It doesn’t contain the duplicate elements because it extends Sorted Set. It does not maintain the insertion of order, but elements are sorted.  It doesn't allow to insert heterogeneous objects if you want to add heterogeneous elements it gives classCastException at runtime. TreeSet uses the data structure which is Red-Black Tree. The complexity time for insert, delete and search operation is O(log n). The complexity time for an operation like printing N elements is O (n) time.

Synchronized TreeSet

TreeSet is not synchronized because if multiple thread access the tree set immediately, Then, at least one thread modifies the set and synchronized externally. It accomplished by synchronizing on some objects that naturally encapsulated the set. The set should be wrapped by using Collections.synchronizedSortedSet method when no such objects exist. To prevent the unsynchronized access to the TreeSet, we have to synchronize at creation time:
TreeSet ts= new TreeSet ();
Set syncSet= Collection.synchronizedSet (ts);
There are two things which remember at the creation and insertion time:
  1. At the insertion time, null not be inserted. Elements get compared to each other and null cannot be compared to any value. If you insert null, then it throws NullPointerException.
  2. If you want default sorting order, then the object should be homogeneous and comparable. Otherwise, it throws a Runtime Exception.
Example:
import java.util.*;
public class TreeSetDemo {
 public static void main (String [] args) {
TreeSet<StringBuffer> ts = new TreeSet<StringBuffer> ();
ts.add (new StringBuffer ("java"));
ts.add (new StringBuffer ("C"));
ts.add (new StringBuffer ("DBMS"));
ts.add (new StringBuffer ("C sharp"));
ts.add (new StringBuffer ("python"));
System.out.println (ts);     // we will get Runtime Exception: ClassCastException
   }   }                    // as StringBuffer does not implements Comparable interface
Output:
Exception in thread "main" java.lang.ClassCastException: java.base/java.lang.StringBuffer cannot be cast to java.base/java.lang.Comparable
at java.base/java.util.TreeMap.compare (TreeMap.java:1291)
at java.base/java.util.TreeMap.put (TreeMap.java:536)
at java.base/java.util.TreeSet.add (TreeSet.java:255)
at TreeSetDemo.main (TreeSetDemo.java:9)
Command exited with non-zero status 1

Constructors of TreeSet

  1. TreeSet t= new TreeSet (): It is the default constructor. It will create the empty TreeSet object.
  2. TreeSet t= new TreeSet (Collection c): It is used when any conversion is needed of any collection object to TreeSet objects.
  3. TreeSet t= new TreeSet (Comparator comp): It is used to create the empty TreeSet that will sort according to their comparator.
  4. TreeSet t= new TreeSet (SortedSet s): This is used to convert the SortedSet object to the TreeSet object.

Methods in TreeSet

  1. add (): It is used to add elements according to their sorting order and unique values.
Example:
import java.io.*;
import java.util.*;
public class AddDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
  } }
Output: TreeSet:
[C sharp, Java, R, Visual Basic, python]
  1. addAll (Collection c): This is used to add all elements of the specified collection in the set.
Example:
import java.io.*;
import java.util.*;
public class AddDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
TreeSet<String> tre = new TreeSet<String>();
tre.add ("React");
tre.add ("AWS");
tree.addAll (tre);
System.out.println ("TreeSet: " + tree);
  } }
Output:
TreeSet: [C sharp, Java, R, Visual Basic, python]
TreeSet: [AWS, C sharp, Java, R, React, Visual Basic, python]
  1. clear (): It is used to clear the elements from the set.
Example:
import java.io.*;
import java.util.*;
public class ClearDemo {
public static void main (String args[]) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
tree.clear ();
System.out.println ("After clearing TreeSet: " + tree);
 } }
Output:
TreeSet: [C sharp, Java, R, Visual Basic, python]
After clearing TreeSet: []
  1. contains (object o): It is used to check the element present in the set or not. If element present, it returns true otherwise return false.
Example:
import java.io.*;
import java.util.*;
public class ContainsDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
System.out.println ("Does the Set contain 'java'?”+tree.contains ("java"));
System.out.println ("Does the Set contain 'R'?" +tree.contains ("R"));
System.out.println ("Does the Set contain 'C sharp'?" + tree.contains ("C sharp"));
    } }
Output:
TreeSet: [C sharp, Java, R, Visual Basic, python]
Does the Set contain 'java'? false
Does the Set contain 'R'? true
Does the Set contain 'C sharp'? true
  1. first (): This method is used to return the first element of the TreeSet.
Example:
import java.io.*;
import java.util.*;
public class FirstDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String>();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
System.out.println ("The first element is: " + tree.first ());
} }
Output:
TreeSet: [C sharp, Java, R, Visual Basic, python]
The first element is: C sharp
  1. last (): This method is used to return the last element of the TreeSet.
Example:
import java.io.*;
import java.util.*;
public class LastDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("Python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
System.out.println ("The last element is: " + tree.last ());
} }
Output:
TreeSet: [C sharp, Java, Python, R, Visual Basic]
The last element is: Visual Basic
  1. headSet (Object to Element): This method is used to return the elements of the TreeSet which is less than the specified element.
Example:
import java.io.*;
import java.util.*;
public class HeadSetDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("Python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
System.out.println ("Elements in head set: " + tree.headSet ("Python"));
}}
Output:
TreeSet: [C sharp, Java, Python, R, Visual Basic]
Elements in head set: [C sharp, Java]
  1. tailSet (Object to Element): This method is used to return the element which is greater than or equal to the Specified element of the TreeSet.
Example:
import java.io.*;
import java.util.*;
public class TailDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("Python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
System.out.println ("Elements in tail set: " + tree.tailSet ("Python"));
}}
Output:
TreeSet: [C sharp, Java, Python, R, Visual Basic]
Elements in tail set: [Python, R, Visual Basic]
  1. subset (object fromElement, object toElement): This method is used to return the element in the range of fromElement to toElement of the TreeSet.
Example: import java.io.*;
import java.util.*;
public class SubsetDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("Python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
System.out.println ("Elements in Subset: " + tree.subSet ("Java”,” Visual Basic"));
}}
Output:
TreeSet: [C sharp, Java, Python, R, Visual Basic]
Elements in Subset: [Java, Python, R]
  1. isEmpty (): It returns true if the set is empty otherwise false.
Example:
import java.io.*;
import java.util.*;
public class EmptyDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("Python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
System.out.println ("Is set empty: " + tree.isEmpty ());
tree.clear ();
System.out.println ("Is set empty: " + tree.isEmpty ());
}}
Output:
TreeSet: [C sharp, Java, Python, R, Visual Basic]
Is set empty: false
Is set empty: true
  1. clone (): It is used to make the same copy of the set.
Example:
import java.io.*;
import java.util.*;
public class CloneDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String>();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
TreeSet clone = new TreeSet ();
clone = (TreeSet) tree.clone ();
System.out.println ("The cloned TreeSet: " + clone);
    } }
Output:
TreeSet: [C sharp, Java, R, Visual Basic, python]
The cloned TreeSet: [C sharp, Java, R, Visual Basic, python]
  1. size (): This method is used to return the size of the set.
Example: import java.io.*;
import java.util.*;
public class SizeDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("Python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
System.out.println ("Size of set: " + tree.size ());
}}
Output:
TreeSet: [C sharp, Java, Python, R, Visual Basic]
Size of set: 5
  1. remove (Object o): It is used to eliminate the particular element from the set.
Example:
import java.io.*;
import java.util.*;
public class RemoveDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("Python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
tree.remove ("Visual Basic");
System.out.println ("After removing: " + tree);
}}
Output:
TreeSet: [C sharp, Java, Python, R, Visual Basic]
After removing: [C sharp, Java, Python, R]
  1. iterator (): Returns the iterator over the elements of the TreeSet.
Example:
import java.io.*;
import java.util.*;
public class IteratorDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("Python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
Iterator value = tree.iterator ();
System.out.println ("The iterator values are: ");
while (value.hasNext ()) {
System.out.println (value.next ());
  } } }
Output:
TreeSet: [C sharp, Java, Python, R, Visual Basic]
The iterator values are:
C sharp
Java
Python
R
Visual Basic
  1. comparator (): It returns comparator used to sort elements in the TreeSet.
Example:
import java.io.*;
import java.util.*;
public class ComparatorDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String> ();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("Python");
tree.add ("C sharp");
System.out.println ("TreeSet: " + tree);
Comparator c=tree.comparator ();
System.out.println ("The comparator value is: "+ c);
        } }
Output:
TreeSet: [C sharp, Java, Python, R, Visual Basic]
The comparator value is: null
  1. descendingSet (): It returns the element in reverse order.
Example:
import java.io.*;
import java.util.*;
public class ReverseDemo {
public static void main (String args []) {
TreeSet<String> tree = new TreeSet<String>();
tree.add ("R");
tree.add ("Java");
tree.add ("Visual Basic");
tree.add ("Python");
tree.add ("C sharp");
TreeSet<String> re = (TreeSet<String>) tree.descendingSet ();
System.out.println ("Without descendingSet (): " +tree);
System.out.println ("With descendingSet (): " + re);
} }

Related Topics

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Java Math getExponent() Method

The getExponent() method of Math class returns the unbiased exponent of the argument. Syntax: public static int getExponent (double d) Parameters: The parameter ‘d’ represents the double value. Return Value: The getExponent () method returns the...

1 minute read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Isomorphic String in Java

In this tutorial, we will understand what is meant by isomorphic String in java. We will also see a Java program to find out if the string is isomorphic or...

4 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

AbstractSet Class in Java

The AbstractSet class is used for the implementation of the Abstract Collection class and interface. It is the part of Collection Frameworks. In the AbstractSet, the implementation is same as the...

3 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.