In this section, we will learn what the Set iterator() method is and how to use it in Java.
What is Java Set iterator() Method?
The Java Set iterator() method is used to get an Iterator object by which we can iterate through the elements of a Set object.
Note: Please check the Iterator interface if you’re not familiar with this interface.
Java Set iterator() Method Syntax:
Iterator<E> iterator()
iterator() Method Parameters:
The method does not take an argument.
iterator() Method Return Value:
The return value of this method is an iterator object.
iterator() Method Exceptions:
The method does not throw an exception.
Example: using Set iterator() method
import java.util.TreeSet; import java.util.Set; import java.util.Iterator; class Main{ public static void main(String[] args) { Set<Integer> ts = new TreeSet<>(); ts.add(1); ts.add(2); ts.add(3); ts.add(0); ts.add(10); Iterator<Integer> iterate = ts.iterator(); while (iterate.hasNext()){ System.out.println(iterate.next()); } } }
Output:
0 1 2 3 10