How to Iterate Java TreeSet Example

This example shows how to iterate TreeSet in Java. The example also shows how to iterate TreeSet using for loop, TreeSet iterator, and forEach method (Java 8).

How to iterate TreeSet in Java?

There are various ways using which we can iterate over all elements of TreeSet as given below.

1. Using enhanced for loop

The enhanced for loop can be used to iterate over TreeSet elements as given below.


2. Using TreeSet Iterator and while loop

We can get the TreeSet Iterator object using the iterator method.

The iterator method returns an iterator over the elements of the TreeSet. Once we get an iterator, we can iterate over elements using the hasNext and next methods and while loop as given below.


One important difference between iterating the TreeSet using an iterator and other methods is that we can remove TreeSet elements using the remove method of the Iterator while iterating. The remove method of the Iterator removes an element from the underlying collection object which is, in this case, a TreeSet object.

The remove method can be called only once per the next method call. The TreeSet iterator throws IllegalStateException exception if the next method has not been called before calling the remove method OR the remove method has been already called after the next method call.

Always make sure to not modify the TreeSet object while iterating it using an iterator other than using the remove method. If that happens, the behavior of the iterator is undefined.

3. Using forEach (Java 8 and later versions)

If you are using Java version 8 or later, you can use the forEach to iterate as given below.


As we can see from the output above, the TreeSet class automatically sorts the elements by their natural ordering (or by using the provided comparator object). So when we iterate the TreeSet, the elements are returned in their sorted order instead of the insertion order.

Please also visit how to iterate over TreeSet elements in reverse order example to know more.


Please let me know your views in the comments section below.

Java 8 TreeSet

About the author




Add Comment


Online Shopping