Write a Java program to iterate TreeSet collection in ascending order


This is a Java program that demonstrates how to use the TreeSet class to store and sort integers in ascending order.

The program first creates a TreeSet object called num, which is a collection of unique elements sorted in ascending order. It adds five integers to the set using the add() method.

Then, the program creates an iterator ite for the num set using the iterator() method. It uses a while loop with the hasNext() method to iterate through the elements of the set and print them in ascending order using the next() method.

Source Code

import java.io.*;
import java.util.*;
public class Ascending_Order
{
	public static void main(String args[])
	{
		TreeSet <Integer> num = new TreeSet <Integer>();
		num.add(70);
		num.add(30);
		num.add(50);
		num.add(20);
		num.add(60);
 
		Iterator <Integer> ite = num.iterator();
		System.out.println("Elements in Ascending order ..");
 
		while(ite.hasNext())
		{
			System.out.println(ite.next());
		}
	}
}

Output

Elements in Ascending order ..
20
30
50
60
70