INTRODUCTION OF TREESET

Introduction Of TreeSet


TreeSet:

  • In set interface if we want to sort the elements we should use Tree Set, because collection.sort( ) method won’t support Set interface, it is exclusive for List interface.

  • By Default, Tree set gives ascending order of output and by default it will use comparable interface for sorting the set elements.

  • Inside Tree set we should add same type elements otherwise we get class cast exception why because by default tree set uses comparable interface.

  • If it contain any derived objs then that corresponding class should implement the comparable interface

Example 1:

 
            
              package com.sdj.pack1;
              import java.util.TreeSet;
              public class TreeSetExp
              {
                 public static void main(String[] args)
                 {
                    TreeSet set1=new TreeSet();
                    set1.add("welcome");
                    set1.add("to");
                    set1.add("SDJ");
                    set1.add("null");
                    set1.add("   ");
                    set1.add(25);
                    set1.add(30);
                    set1.add(40);
                    System.out.println("The Elements are:"+set1);
                 }
              } 
                  
    Note
      If we run above prog we will get Class Cast Exception because by default Tree Set uses comparable interface by using it we can compare same type of elements but not different type elements, here we are using different type elements i.e some are String type and some are Integer type , and so we get ClassCastException.
     
    Note
      To make success the above example, we should add same type elements to treeset like below example

Example 2:

 
            
              packagecom.sdj;
              public class TreeSetExpl
              {
                 public static void main(String[] args)
                 {
                    TreeSet set=new TreeSet();
                    set.add("welcome");
                    set.add("to");
                    set.add("SDJ");
                    set.add("null");
                    set.add("   ");
                    set.add("25");
                    set.add("30");
                    set.add("40");
                    set.add("$abc");
                    set.add("WELCOME");
                    set.add("*abc");
                    set.add("_xyz");
                    System.out.println(" Tree Set Elements are:"+set);
                 }
              } 
             

Output:

Tree Set Elements are: [ , $abc, *abc, 25, 30, 40, WELCOME, _xyz, SDJ, null, to, welcome]
    Note
      By using sorting operation the output order will be shown as below The sorting performance is
    • First it will see spaces (“ “).

    • Special Characters ($,*).

    • Numbers (0, 1, 2, 3……………).

    • Uppercase letters (ABCDEF…….Z).

    • Under Score ( _123, _ABC, _abc,¬…..).

    • Lowercase letters (abcd………z).

Some methods inside Set:


first( ):

  • It will returns first element currently in the sorted set.

  • If the set is empty we call first( ) method and we get one exception i.eNo Such Element Exception.

last( ) :

  • The last( ) method will return last element from the sorted set.

headSet( ):

  • The headSet( ) method will take one input type as object.

  • If we give any value inside headset( ) method that value is boundary value for that set and that is excluded printing remaining values as output before that excluded value.

  • Syntax:

      public sortedsetheadset(object obj);

  • Passing object is excluded in headset.

tailSet( ):

  • The tailSet( ) method also take one object as input.

  • Syntax:

      public sortedset headset(object obj);

  • If we give any value to tail set method then it is boundary value (i.e Included) here boundary value also included printing remaining values as output after that included value..

Example 3:

 
            
              package com.sdj.pack1;
              import java.util.TreeSet;
              public class TreeSetExp
              {
                 public static void main(String[] args)
                 {
                    TreeSet set=new TreeSet();
                    set.add("welcome");
                    set.add("to");
                    set.add("SDJ");
                    set.add("null");
                    set.add("   ");
                    set.add("25");
                    set.add("30");
                    set.add("40");
                    set.add("$abc");
                    set.add("WELCOME");
                    set.add("*abc");
                    set.add("_xyz");
                    System.out.println("Tree Set Elements are:"+set);
                 }
              } 
            

Output:

Tree Set Elements are: [ , $abc, *abc, 25, 30, 40, WELCOME, _xyz, SDJ, null, to, welcome]
    Note

    Case:

    • If we pass any element to head set and if passed element is not available in the set . then the passed element is same type of the existing element then JRE checks if that element is available in the set where its position will come. S

    • For example we pass ‘190’ as input to head set in the above example i.e.Set1.headset(190);

    • In above tree set example ‘190’ is not there if it is there in set that place will come after ‘80’ . so we will get o/p of all the elements before to that position i.e[10, 25, 30, 40, 62, 70, 90].Set1.headset(-10);

    • For example if we pass ‘-10’ has head set. ‘-10’ is not available in the list then JRE looks where its position will come but before that if there are no elements before to that position then we will get output as empty.

    Case2:

    • If we pass different element then we will get class cast exception.Example set1.headset(“abc”);

tailSet( ):

  • In case tailset( ) we pass ‘190’ as input to tailset( ) but there are no elements after this value so that we will get output as empty.

Example 4:

 
            
              package com.sdj.pack1;
              import java.util.TreeSet;
              public class TreeSetExp2
              {
                 public static void main(String[] args)
                 {
                    TreeSet set=new TreeSet();
                    set.add(25);
                    set.add(30);
                    set.add(40);
                    set.add(70):
                    set.add(10);
                    System.out.println("Elements in set are:"+set);
                    System.out.println("The head set elements by passing ‘190’ are:"+set.headSet(190));
                    System.out.println("The head set elements by passing ‘-10’ are:"+set.headSet(-10));
                    System.out.println("The head set elements by passing ‘190’ are:"+set.tailSet(190));
                    System.out.println("The head set elements by passing ‘-10’ are:"+set.tailSet(-10));
                 }
              } 
            

Output:

Elements in set are:[10, 25, 30, 40, 70] The head set elements by passing ‘190’ are:[10, 25, 30, 40, 70] The head set elements by passing ‘-10’ are:[] The head set elements by passing ‘190’ are:[] The head set elements by passing ‘-10’ are:[10, 25, 30, 40, 70]

subSet( ):

  • The subSet( ) method will take inputs as two object types.In this first object value is included and second object type value is excluded and prints remaining values as the output.

Syntax:

    public sortedset headset(object obj);

    Note
      The starting element should be less than the ending element otherwise we will get Illegal argument exception like below

Example 5:

 
            
              packagecom.sdj;
              public class TreeSetExpl1
              {
                 public static void main(String[] args)
                 {
                    TreeSet set1=newTreeSet();
                    set1.add(25);
                    set1.add(30):
                    set1.add(70);
                    set1.add(40);
                    set1.add(30);
                    set1.add(10);
                    set1.add(62):
                    System.out.println("The Elements  in set1 are:"+set1);
                    System.out.println("The subset elements are:"+set1.subSet(25, 65));
                    System.out.println("The subset elements are:"+set1.subSet(40, 190));
                    System.out.println("The subset elements are:"+set1.subSet(-10, 70));
                    /* System.out.println("The subset elements are:"+set1.subSet(190,80)); */
                    /* why because in  subset method starting index should be less than the */
               /* ending index else we will getjava.lang.IllegalArgumentException.at run time */
                 }
              } 
            

Output:

The Elements in set1 are:[10, 25, 30, 40, 62, 70] The subset elements are:[25, 30, 40, 62] The subset elements are:[40, 62, 70] The subset elements are:[10, 25, 30, 40, 62]

Sorting elements in tree set through comparator interface

  • By default tree set will sort the elements by using comparable interface .

  • By using comparable interface we can able to sort the elements based on only one condition at any point of time.

  • If we use the comparator interface for sorting tree elements we can use different types of conditions based on the requirement.

  • Below example illustrates the sorting Person class objects based on age and height depending on the requirement.

Example 5:

 
            
              package com.sdj;
              class Person
              {
                 int age;
                 double height;
                 Person(int age,double height)
                 {
                    this.age=age;
                    this.height=height;
                 }
                 public String toString()
                 {
                    return "age:"+age+", height"+height;
                 }
                 public int compareTo(Object obj)
                 {
                    return this.age-((Person)obj).age;
                 }
              }
              class SortBasedOnAge implements Comparator
              {
                 public int compare(Object obj1, Object obj2)
                 {
                    Person p1=(Person) obj1;
                    Person p2=(Person) obj2;
                    return p1.age-p2.age;
                 }
              }
              class SortBasedOnHeight implements Comparator
              {
                 public int compare(Object obj1, Object obj2)
                 {
                    Person p1=(Person) obj1;
                    Person p2=(Person) obj2;
                    return  ((int) (p1.height-p2.height));
                 }
              }
              public class TreeSetDemo
              {
                 public static void main(String[] args)
                 {
                    TreeSet set=new TreeSet(new SortBasedOnAge());
                    set.add(new Person(30,6.5));
                    set.add(new Person(20,4.5));
                    set.add(new Person(40,5.5));
                    set.add(new Person(60,2.5));
                    System.out.println("Sort Based On Age");
                    System.out.println(set);
                    TreeSet set1=new TreeSet(new SortBasedOnHeight());
                    set1.addAll(set);
                    System.out.println("Sort Based On Height");
                    System.out.println(set1);
                 }
              } 
            

Output:

Sort Based On Age: [age:20, height4.5, age:30, height6.5, age:40, height5.5, age:60, height2.5] Sort Based On Height: [age:60, height2.5, age:20, height4.5, age:40, height5.5, age:30, height6.5]