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

TreeSet()
//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();
    tDemo.add("d");
    tDemo.add("e");
    tDemo.add("a");
    tDemo.add("b");
    tDemo.add("f");
    tDemo.add("c");

    System.out.println("TreeSet contents : ");
    System.out.println(tDemo);
    /*IN this java treeset example we are creating Hashset and then converting it to TreeSet*/
    HashSet hDemo = new HashSet();
    hDemo.add("d");
    hDemo.add("f");
    hDemo.add("e");
    hDemo.add("g");
    hDemo.add("i");
    hDemo.add("h");

    System.out.println("HashSet contents : ");
    //HashSet Not in order
    System.out.println(hDemo);
    
    /*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]
a
f

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

0 comments:

Post a Comment