Java TreeSet class

The element of TreeeSet class are stored in Binary Search Tree, which means that access time are faster. In order to add object of user define classes to a Tree Base Collection, sorting logic must be define for the classes because in order to add elements Binary Search Tree required sorting order.

Sorting logic can be define for a class using either of the following interfaces-

  1. java.lang.Comparable
  2. java.util.comparator

Main Point

  • TreeSet is sorted collection class
  • Sorting of objects in TreeSet in natural order by default or we can provide comparator class reference for customized sorting.
  • While working with large amount of data access and retrieval is faster with TreeSet.
SN Constructor Description
1 TreeSet() Default Constructor
2 TreeSet(Collection e) TreeSet from Collection C
3 TreeSet(Comparator c) TreeSet with custom ordering as per Comparator
4 TreeSet(SortedSet e) TreeSet that contains the elements of ss

SN Method Description
1 void add(Object o) Adds the specified element to this set if it is not already present
2 void clear() Removes all of the elements from this set.
3 Object first() Returns the first (lowest) element currently in this sorted set.
4 Object last() Returns the last (highest) element currently in this sorted set.
5 boolean isEmpty() Returns true if this set contains no elements
6 boolean remove(Object o) Removes the specified element from this set if it is present
7 SortedSetsubSet(Object fromElement, Object toElement) Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive

Example of TreeSet class

	import java.util.TreeSet;

	public class TreeSetDemo {

	public static void main(String[] args) {

	TreeSet playerSet = new TreeSet();











	playerSet.add("Sachin"); // This is duplicate element so will not be added again

	//below will print list in alphabetic order

	System.out.println("Original Set:" + playerSet);

	System.out.println("First Name: "+ playerSet.first());

	System.out.println("Last Name: "+ playerSet.last());

	TreeSet newPlySet = (TreeSet) playerSet.subSet("Mahi", "Virat");

	System.out.println("Sub Set: "+ newPlySet);






Original Set:[Bhajji, Gautam, Ishant, Mahi, Pathan, Sachin, Umesh, Virat, Viru,Zahir]

First Name: Bhajji

Last Name: Zahir

Sub Set: [Mahi, Pathan, Sachin, Umesh]