Java TreeSet iterator() Method Example

The iterator() method of java.util.TreeSet class will return an iterator over the elements in this set in ascending order.

Signature

public Iterator<E> iterator() 

This method returns an iterator over the elements in this set in ascending order. Returned iterator will be a fail-fast iterator

Example

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

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

public class IteratorMethodTreeSetExample {
    public static void main(String args[])
    {
        // create an empty TreeSet
        TreeSet treeSet1 = new TreeSet();
        
        // use add() method to add elements to the TreeSet
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");
        treeSet1.add("Element4");
        
        //Iterating elements of the TreeSet
        System.out.println("Elements of the TreeSet");
        Iterator it = treeSet1.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
    }
}

Output

Elements of the TreeSet
Element1
Element2
Element3
Element4

Leave a Reply

Your email address will not be published. Required fields are marked *