What is the TreeSet.iterator() function in Java?

In this shot, we will discuss how to use the TreeSet.iterator() method in Java. The TreeSet.iterator() method is present in the Iterator class inside the java.util package. TreeSet.iterator() is used to iterate over the TreeSet and returns the value of elements as iterators of the TreeSet.

Syntax

Iterator iterator = set.iterator();

Parameters

The TreeSet.iterator() method does not take any parameters.

Return value

TreeSet.iterator() iterates over the elements of the TreeSet and returns the values (iterators).

Code

Let’s look at the code snippet.

import java.io.*;
import java.util.*;
class Main
{
public static void main(String args[])
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
tree_set.add(1);
tree_set.add(8);
tree_set.add(5);
tree_set.add(3);
tree_set.add(0);
System.out.println("TreeSet: " + tree_set);
Iterator val = tree_set.iterator();
System.out.print("The iterator values are: ");
while (val.hasNext())
System.out.print(val.next()+" ");
}
}

Explanation

  • In lines 1 and 2 we import the required packages.

  • In line 4 we make a Main class.

  • In line 6 we make a main function.

  • In line 8 we declare a TreeSet of Integer type.

  • In lines 9 to 13 we add the elements into the TreeSet with the TreeSet.add() method.

  • In line 14 we display the TreeSet.

  • In line 16 we create an iterator and call the TreeSet.iterator() method.

  • In line 17 we display the message with the values of the iterator.

  • In line 18 we use a while loop to access and display the value of the next element through the iterator_name.next() method when the condition is true, i.e., if the iterator object has another element after its value.

Free Resources