VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-iterate-over-the-elements-in-a-treeset-in-natural-order-in-java/

⇱ How to Iterate Over the Elements in a TreeSet in Natural Order in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Iterate Over the Elements in a TreeSet in Natural Order in Java?

Last Updated : 23 Jul, 2025

In Java, to iterate over the elements of a TreeSet in their Natural Order, one must either use a custom comparator provided or traverse the elements in ascending order based on their natural ordering. A TreeSet in Java keeps up with its components in arranged requests.

In this article, we will learn how to iterate over the elements in a TreeSet in natural order in Java.

Syntax

for (Integer Value : treeSet)
{
System.out.print(Value);
}

Program to Iterate Over the Elements in a TreeSet in Natural Order in Java

Below is the implementation using an Enhanced For loop to iterate over the elements in a TreeSet in natural order utilizing a basic Java program:


Output
Iterating over TreeSet in natural order:
1
2
5
8

Explanation of the Program:

  • In the above program, a TreeSet is created to store integers.
  • Elements are added to the TreeSet.
  • And then the program iterates over the elements using an enhanced for loop (for-each loop) to print them in natural order.
Comment