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:
- 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.
- 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
- TreeSet t= new TreeSet (): It is the default constructor. It will create the empty TreeSet object.
- TreeSet t= new TreeSet (Collection c): It is used when any conversion is needed of any collection object to TreeSet objects.
- TreeSet t= new TreeSet (Comparator comp): It is used to create the empty TreeSet that will sort according to their comparator.
- TreeSet t= new TreeSet (SortedSet s): This is used to convert the SortedSet object to the TreeSet object.
Methods in TreeSet
- 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]
- 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]
- 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: []
- 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
- 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
- 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
- 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]
- 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]
- 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]
- 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
- 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]
- 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
- 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]
- 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
- 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
- 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);
} }