java.util.TreeSet.iterator() Method


Advertisements


Description

The iterator() method is used to return an iterator over the elements in this set in ascending order.

Declaration

Following is the declaration for java.util.TreeSet.iterator() method.

public Iterator<E> iterator()

Parameters

  • NA

Return Value

The method call returns an iterator over the elements in this set in ascending order.

Exception

  • NA

Example

The following example shows the usage of java.util.TreeSet.iterator() method.

package com.tutorialspoint;

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

public class TreeSetDemo {
   public static void main(String[] args) {
   // creating a TreeSet 
   TreeSet <Integer>treeadd = new TreeSet<Integer>();
     
   // adding in the tree set
   treeadd.add(1);
   treeadd.add(13);
   treeadd.add(17);
   treeadd.add(2);
     
   // create ascending iterator
   Iterator iterator;
   iterator = treeadd.iterator();
     
   // displaying the Tree set data
   System.out.println("Tree set data in ascending order: ");     
   while (iterator.hasNext()){
   System.out.println(iterator.next() + " ");
   }
   }     
}

Let us compile and run the above program, this will produce the following result.

Tree set data in ascending order: 
1 
2 
13 
17 

java_util_treeset.htm

Advertisements