×

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

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.