How to Iterate Over the Elements in a TreeSet in Natural Order in Java?
Last Updated :
07 Feb, 2024
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
import java.util.TreeSet;
public class TreeSetIterationExample
{
public static void main(String[] args)
{
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add( 5 );
treeSet.add( 2 );
treeSet.add( 8 );
treeSet.add( 1 );
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.
Share your thoughts in the comments
Please Login to comment...