Tutorials

Collection Programs


TreeSet Traversal


In this chapter, our task is:

  • We will create a TreeSet
  • We will add elements to TreeSet (duplicate as well)
  • Traverse the TreeSet using Iterator 
  • We will print the set

TreeSet stores the elements in sorted order.

Default sorting is done in ascending order.

Example: Add and traverse the elements of TreeSet in java.


package javaRadarTreeSet;

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

public class TreeSetExample {

      public static void main(String[] args) {

         //Create treeset
           TreeSet treeSet = new TreeSet();

          //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 setIterator = treeSet.iterator();

               while(setIterator.hasNext()){

                   String element = setIterator.next();
                   System.out.println(element);

                }

        }

}

OUTPUT

Krishna
Manish
Mithilesh
Omjit
Puja
Rita
Shweta
 
As all the elements are String object so the sorting is done in lexicographically. It means they are sorted in alphabetical order. 
Element starting with A will be printed first then with B and so on. 
In case we have two elements starting with same alphabet for example, Manish and Mithilesh 
Then second alphabet will be compared where Manish has 'a' and Mithilesh has 'i'. So Manish qualifies lexicographically.

 



Please Share this page
Views : 26