Skip to Content

Iterate through elements of Java TreeSet example

  1. /*
  2.   Iterate through elements of Java TreeSet example
  3.   This Java Example shows how to iterate through elements Java TreeSet object.
  4. */
  5.  
  6. import java.util.TreeSet;
  7. import java.util.Iterator;
  8.  
  9. public class IterateThroughElementsOfTreeSetExample {
  10.  
  11.   public static void main(String[] args) {
  12.  
  13.     //create object of TreeSet
  14.     TreeSet tSet = new TreeSet();
  15.    
  16.     //add elements to TreeSet object
  17.     tSet.add(new Integer("1"));
  18.     tSet.add(new Integer("2"));
  19.     tSet.add(new Integer("3"));
  20.    
  21.     //get the Iterator
  22.     Iterator itr = tSet.iterator();
  23.    
  24.     System.out.println("TreeSet contains : ");
  25.     while(itr.hasNext())
  26.       System.out.println(itr.next());
  27.   }
  28. }
  29.  
  30. /*
  31. Output would be
  32. TreeSet contains :
  33. 1
  34. 2
  35. 3
  36. */