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:

packagejavaRadarTreeSet;
importjava.util.Iterator;
importjava.util.TreeSet;
public class TreeSetExample {
      public static void main(String[] args) {
            //Create treeset
            TreeSet<String> treeSet = newTreeSet<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

Source link

TreeSet in java

Leave a Reply

Your email address will not be published. Required fields are marked *