Home » Core Java » util » TreeSet » TreeSet Iterator example

About Ilias Tsagklis

Avatar photo
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

TreeSet Iterator example

In this example we shall show you how to get a TreeSet Iterator. To get a TreeSet Iterator one should perform the following steps:

  • Create a new TreeSet.
  • Populate the set with elements, with add(E e) API method of TreeSet.
  • Obtain an Iterator of the set, with iterator() API method of TreeSet. It is an iterator over the elements in this set in ascending order.
  • Iterate over the set’s elements, with hasNext(), next() API methods of Iterator, to get the TreeSet’s elements,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.util.TreeSet;
import java.util.Iterator;
public class TreeSetIteratorExample {
  public static void main(String[] args) {
    // Create a TreeSet and populate it with elements
    TreeSet treeSet = new TreeSet();
    // To get the Iterator use the iterator() operation
    Iterator it = treeSet.iterator();
    System.out.println("Elements in TreeSet :");



Elements in TreeSet :

This was an example of how to get a TreeSet Iterator in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments