Java Utility Library

Java TreeSet - iterator() Method



The java.util.TreeSet.iterator() method returns an iterator over the elements in this set in ascending order.

Syntax

public Iterator<E> iterator()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns an iterator over the elements in this set in ascending order.

Exception

NA.

Example:

In the example below, the java.util.TreeSet.iterator() method returns an iterator over the elements of the given set.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treeset
    TreeSet<Integer> MySet = new TreeSet<Integer>();

    //populating the set
    MySet.add(40);
    MySet.add(20);
    MySet.add(10);
    MySet.add(30);

    //print the content of the set
    System.out.println("MySet contains: " + MySet);

    //creating an iterator
    Iterator<Integer> itr = MySet.iterator();

    //print the content of the iterator
    System.out.println("The iterator values are: ");
    while(itr.hasNext())
      System.out.println(itr.next()); 
  }
}

The output of the above code will be:

MySet contains: [10, 20, 30, 40]
The iterator values are: 
10
20
30
40

❮ Java.util - TreeSet