Sunday 29 July 2012

Iterate through elements of Java TreeSet example


This Java Example shows how to iterate through elements of Java TreeSet object.

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

public class IterateThroughElementsOfTreeSetExample {

 public static void main(String[] args) {

  // create object of TreeSet
  TreeSet tSet = new TreeSet();

  // add elements to TreeSet object

  tSet.add(1);
  tSet.add(2);
  tSet.add(3);

  // get the Iterator
  Iterator itr = tSet.iterator();

  System.out.println("Using Iterator - TreeSet contains : ");
  while (itr.hasNext())
   System.out.println(itr.next());
  /**
   * We can also use for-each loop available since java1.5 for iterating
   * through elements.
   **/
  System.out.println("Using for-each loop  - TreeSet contains : ");

  for (Object elmt : tSet) {
   System.out.println(elmt);
  }
 }
}


The output is:


Using Iterator - TreeSet contains :
1
2
3
Using for-each loop  - TreeSet contains :
1
2
3

No comments:

Post a Comment