TreeSet in Java

How to use TreeSet in Java


TreeSet in java is a class which implements Set interface. Let see few characteristics of TreeSet in java before taking look at java treeset example.

TreeSet in java

1. TreeSet in java guarantees sorted set of elements which are arranged in ascending order.
2. TreeSet in java provides log(n) time for basic operations such as add, remove and contains.
3. TreeSet in java is not synchronized , we need to synchronize it externally using Collections.synchronizedSortedSet.

TreeSet in java provides four constructors such as

//Creates empty TreeSet, once filled sorted in natural order.

TreeSet(Collection c)
//Creates a TreeSet from given Collection, sorted in natural order.

TreeSet(Comaparator c)
//Creates a new and empty TreeSet but sorted 
//according to the Comparator passed.

TreeSet(SortedSet s)
//As we can see , we are passing the SortedSet as argument , it creates a 
//TreeSet with same set in same sorted order.

Now Lets see the java treeset example :
/*IN following java TreeSet example we are creating new TreeSet instance and adding elements to it using add method */
public class TreeSetDemo {

  public static void main(String[] args) {

    TreeSet tDemo = new TreeSet();

    System.out.println("TreeSet contents : ");
    /*IN this java treeset example we are creating Hashset and then converting it to TreeSet*/
    HashSet hDemo = new HashSet();

    System.out.println("HashSet contents : ");
    //HashSet Not in order
    /*Converting HashSet to TreeSet after adding elements*/
    TreeSet tDemo2 = new TreeSet( hDemo );
    System.out.println( tDemo2 );
    Object tDemoLow = tDemo.first(); // Gives firt item in the set
    Object tDemoHigh = tDemo.last(); // Gives Last item in the set
    System.out.println( tDemoLow );
    System.out.println( tDemoHigh );


Output :
TreeSet contents :
[a, b, c, d, e, f]
HashSet contents :
[f, g, d, e, h, i]
[d, e, f, g, h, i]

Treeset in java and HashSet in java both guarantees that there is no duplicate element in collection.
TreeSet in java offers some useful methods to handle the ordered set such as first(), last(), headSet() and tailSet() etc.
As we saw in java treeset example , often adding elements to HashSet and then converting that collection to TreeSet is faster than directly creating TreeSet in java.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment