Write a Java program to iterate TreeSet collection in descending order


This is a Java program that demonstrates how to use the descendingIterator() method of the TreeSet class to iterate over the elements of a set in descending 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 a descending iterator ite for the num set using the descendingIterator() method. It uses a while loop with the hasNext() method to iterate through the elements of the set and print them in descending order using the next() method.

Source Code

import java.io.*;
import java.util.*;
public class Descending_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.descendingIterator();
		System.out.println("Elements in Descending Order ..");
		while (ite.hasNext())
		{
			System.out.println(ite.next());
		}
	}
}

Output

Elements in Descending Order ..
70
60
50
30
20