Open In App

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

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Java




// Java program to iterate over the elements in a TreeSet in natural order
import java.util.TreeSet;
public class TreeSetIterationExample 
{
    public static void main(String[] args) 
    {
        // Create a TreeSet with elements of type Integer
        TreeSet<Integer> treeSet = new TreeSet<>();
  
        // Add elements to the TreeSet
        treeSet.add(5);
        treeSet.add(2);
        treeSet.add(8);
        treeSet.add(1);
  
        // Iterate over the TreeSet in natural order
        System.out.println("Iterating over TreeSet in natural order:");
        for (Integer element : treeSet) 
        {
            System.out.println(element);
        }
    }
}


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.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads