Java TreeSet iterator() Methods Tutorial

In this section, we will learn what the TreeSet iterator() method is and how to use it in Java.

What is Java TreeSet iterator() Method?

The Java TreeSet iterator() method is used to return an Iterator object by which we can iterate through the elements of a TreeSet object.

Note: you can check the Iterator interface if you’re not familiar with this interface.

Java iterator() Method Syntax:

public 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 object that implemented the Iterator interface.

Note: iterator will return elements in an ascending order.

iterator() Method Exceptions:

The method does not throw an exception.

Example: using TreeSet iterator() method

import java.util.TreeSet; 
import java.util.Iterator; 
class Main{
    public static void main(String[] args) {
        TreeSet<Integer> ts = new TreeSet<>();
        ts.add(1);
        ts.add(2);
        ts.add(3);
        ts.add(0);
        ts.add(10);
        ts.add(30);

        Iterator<Integer>iterate = ts.iterator();
        while (iterate.hasNext()){
            System.out.println(iterate.next());
        }
    }
}

Output:

0

1

2

3

10

30
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies