Java program to iterate TreeSet collection in descending order

Given a TreeSet collection, we have to iterate it in descending order.
Submitted by Nidhi, on June 06, 2022

Problem Solution:

In this program, we will create a TreeSet collection with integer elements. Then we will use the descendingIterator() method to iterate created TreeSet collection in the descending order.

Program/Source Code:

The source code to iterate the TreeSet collection in descending order is given below. The given program is compiled and executed successfully.

Example of TreeSet.descendingIterator() Method in Java

// Java program to iterate TreeSet collection 
// in descending order

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String args[]) {
    TreeSet < Integer > tree = new TreeSet < Integer > ();

    tree.add(25);
    tree.add(20);
    tree.add(35);
    tree.add(30);

    Iterator < Integer > iterator = tree.descendingIterator();

    System.out.println("Elements in descending order:");

    while (iterator.hasNext()) {
      System.out.println("Value : " + iterator.next());
    }
  }
}

Output:

Elements in descending order:
Value : 35
Value : 30
Value : 25
Value : 20

Explanation:

In the above program, we imported the "java.util.*", "java.io.*" packages to use the TreeSet class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created a TreeSet collection tree and added integer elements using add() method. Then we used the descendingIterator() method to get elements of the TreeSet collection and printed them in the descending order.

Java TreeSet Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.