TreeSet in java

TreeSet extends AbstractSet and implements the NavigableSet interface. It maintains ascending order for its elements i.e. elements will be in sorted form.

  • Just like HashSet, the Java TreeSet class contains unique elements only.
  • The access and retrieval times of the TreeSet class are very fast.
  • It does not give access to the null element.
  • It maintains the ascending order.
  • It is non-synchronized.

Hierarchy of the TreeSet class:

The NavigableSet interface is implemented by the Java TreeSet class which extends SortedSet, Set, Collection, and Iterable interfaces in hierarchical order.

TreeSet class declaration:

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable

TreeSet class Constructors:

Constructor Description
TreeSet() It will create an empty tree set that will be sorted in ascending order according to the natural order of the tree set.
TreeSet(Collection<? extends E> c) It will create a new tree set that contains the elements of the collection c.
TreeSet(Comparator<? super E> comparator) It will create an empty tree set that will be sorted according to the given comparator.
TreeSet(SortedSet<E> s) It will create a TreeSet that contains the elements of the given SortedSet.

Methods of Java TreeSet class:

S.No. Method Description
1 boolean add(E e) It will add the specified element to this set if it is not already present.
2 boolean addAll(Collection<? extends E> c) It will add all of the elements in the specified collection to this set.
3 E ceiling(E e) It will get the equal or closest greatest element of the specified element from the set, or null there is no such element.
4 Comparator<? super E> comparator() It will get the comparator that arranges elements in order.
5 Iterator descendingIterator() It will iterate the elements in descending order.
6 NavigableSet descendingSet() It will get the elements in reverse order.
7 E floor(E e) It will get the equal or closest least element of the specified element from the set, or null there is no such element.
8 SortedSet headSet(E toElement) It will get the group of elements that are less than the specified element.
9 NavigableSet headSet(E toElement, boolean inclusive) It will get the group of elements that are less than or equal to(if, inclusive is true) the specified element.
10 E higher(E e) It will get the closest greatest element of the specified element from the set, or null there is no such element.
11 Iterator iterator() It will iterate the elements in ascending order.
12 E lower(E e) It will get the closest least element of the specified element from the set, or null there is no such element.
13 E pollFirst() It will retrieve and eliminate the lowest(first) element.
14 E pollLast() It will retrieve and eliminate the highest(last) element.
15 Spliterator spliterator() It will create a late-binding and fail-fast spliterator over the elements.
16 NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) It will get a set of elements that lie between the given range.
17 SortedSet subSet(E fromElement, E toElement)) It will get a set of elements that lie between the given range which includes fromElement and excludes toElement.
18 SortedSet tailSet(E fromElement) It will get a set of elements that are greater than or equal to the specified element.
19 NavigableSet tailSet(E fromElement, boolean inclusive) It will get a set of elements that are greater than or equal to (if, inclusive is true) the specified element.
20 boolean contains(Object o) It will get true if this set contains the specified element.
21 boolean isEmpty() It will get true if this set contains no elements.
22 boolean remove(Object o) It will eliminate the specified element from this set if it is present.
23 void clear() It will eliminate all of the elements from this set.
24 Object clone() It will get a shallow copy of this TreeSet instance.
25 E first() It will get the first (lowest) element currently in this sorted set.
26 E last() It will get the last (highest) element currently in this sorted set.
27 int size() It will get the number of elements in this set.

TreeSet example:

TreeSetTest.java

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
 
/**
 * This class is used to show the TreeSet functionality.
 * @author w3spoint
 */
public class TreeSetTest {
	public static void main(String args[]){
		//Create TreeSet object.
		Set treeSet = new TreeSet();
 
		//Add objects to the HashSet.
		treeSet.add("Roxy");
		treeSet.add("Sunil");
		treeSet.add("Sandy");
		treeSet.add("Munish");
		treeSet.add("Pardeep");
 
		//Print the TreeSet object.
		System.out.println("TreeSet elements:");
		System.out.println(treeSet);
 
		//Print the TreeSet elements using iterator.
		Iterator iterator=treeSet.iterator();
		System.out.println("TreeSet elements using iterator:");
		while(iterator.hasNext()){  
		   System.out.println(iterator.next());  
		}  
	}
}

Output:

TreeSet elements:
[Munish, Pardeep, Roxy, Sandy, Sunil]
TreeSet elements using iterator:
Munish
Pardeep
Roxy
Sandy
Sunil

Example 1: Traversing elements in descending order:

import java.util.*;  
public class TreeSetExample{  
 public static void main(String args[]){  
 TreeSet<String> set=new TreeSet<String>();  
         set.add("AA");  
         set.add("BB");  
         set.add("CC");  
         System.out.println("Traversing element through Iterator in descending order");  
         Iterator i=set.descendingIterator();  
         while(i.hasNext())  
         {  
             System.out.println(i.next());  
         }  
 
 }  
}

Output:

Example 2: To retrieve and remove the highest and lowest Value:

import java.util.*;  
public class TreeSetExample{  
 public static void main(String args[]){  
 TreeSet<Integer> set=new TreeSet<Integer>();  
         set.add(10);  
         set.add(40);  
         set.add(30);  
         set.add(20);  
         System.out.println("Lowest Value: "+set.pollFirst());  
         System.out.println("Highest Value: "+set.pollLast());  
 }  
}

Output:

Example 3: To perform various NavigableSet operations:

import java.util.*;  
class TreeSetExample{  
 public static void main(String args[]){  
  TreeSet<String> set=new TreeSet<String>();  
         set.add("XYZ");  
         set.add("XZY");  
         set.add("YZX");  
         set.add("ZYX");  
         set.add("YXZ");  
         System.out.println("Initial Set: "+set);  
 
         System.out.println("Reverse Set: "+set.descendingSet());  
 
         System.out.println("Headset: "+set.headSet("YZX", true));  
 
         System.out.println("SubSet: "+set.subSet("XYZ", false, "YXZ", true));  
 
         System.out.println("TailSet: "+set.tailSet("YZX", false));  
 }  
}

Output:

Example 4: To perform various SortedSetSet operations.

import java.util.*;  
public class TreeSetExample{  
 public static void main(String args[]){  
  TreeSet<String> set=new TreeSet<String>();  
         set.add("XYZ");  
         set.add("XZY");  
         set.add("YZX");  
         set.add("ZYX");  
         set.add("YXZ");
 
         System.out.println("Initial Set: "+set);  
 
         System.out.println("Headset: "+set.headSet("YZX"));  
 
         System.out.println("SubSet: "+set.subSet("XYZ", "YXZ"));  
 
         System.out.println("TailSet: "+set.tailSet("YZX"));  
 }  
}

Output:

Next Topic: ArrayList in java with example.
Previous Topic: LinkedHashMap in java with example.

Please Share