Saturday, 16 September 2017

TreeSet in java


TreeSet 
is a class that implements Set interface and extends AbstractSet class. By default, elements in TreeSet class is stored in ascending order (see example given below).


Key feature of TreeSet

1.     TreeSet contains only unique elements.
2.     Maintains ascending order (by default). 
3.     Access and retrival time is fast in TreeSet.


Now let’s look at the ways in which you can create TreeSet in java,
  • ·        TreeSet <E> mySet = new TreeSet<E>();     //<E> denotes generics
  • ·        TreeSet <E> mySet = new TreeSet<E>( Collection c);     //<E> denotes generics


Simple Example:

package javaRadarTreeSet;

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

      public static void main(String[] args) {
            //Create treeset
            TreeSet<String> treeSet = new TreeSet<String>();
            //Add elements to treeset
            treeSet.add("Omjit");
            treeSet.add("Krishna");
            treeSet.add("Mithilesh");
            treeSet.add("Manish");
            treeSet.add("Puja");
            treeSet.add("Shweta");
            treeSet.add("Rita");

            //Traverse the elements of treeset
            Iterator<String> setIterator = treeSet.iterator();
            while(setIterator.hasNext()){
                  String element = setIterator.next();
                  System.out.println(element);
            }

      }

}
OUTPUT:
Krishna
Manish
Mithilesh
Omjit
Puja
Rita
Shweta

Now let’s look at different ways in which you can use the TreeSet that you created. 
Click on each link to read about them.

TreeSet operations

·         Sort the elements in TreeSet  --> (by default its sorted in ascending order)
·         Search element in TreeSet
·         Remove element from a particular index in TreeSet

Traverse TreeSet

·         Traverse TreeSet using Iterator
·         Traverse TreeSet using ListIterator
·         Traverse TreeSet using Enumeration
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.