TreeSet iterator() in Java

iterator(): This method is available in java.util.TreeSet class of Java.

Syntax:

Iterator<K> java.util.TreeSet.iterator()

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

Parameters: NA

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

Exceptions: NA

Approach

Java

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

public class TreeSetiterator {
    public static void main(String[] args) {

        TreeSet<String> treeSet = new TreeSet<String>();

        treeSet.add("Hello");
        treeSet.add("Java");
        treeSet.add("Program");
        treeSet.add("C++");

        Iterator<String> iterator = treeSet.iterator();

        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");

        }

    }
}

Output:

C++ Hello Java Program 

No comments:

Post a Comment