Friday, November 21, 2025
HomeLanguagesJavaNavigableSet descendingSet() method in Java

NavigableSet descendingSet() method in Java

The descendingSet() method of NavigableSet interface in Java is used to return a reverse order view of the elements contained in this set. The descending set is backed by this set, so any changes to the set are reflected in the descending set, and vice-versa. If any of the set is modified while an iteration over other set is in progress, the results of the iteration are undefined.

Syntax:

Iterator<E> descendingSet()

Where, E is the type of elements maintained by this Set container.

Parameters: This function does not accepts any parameter.

Return Value: It returns a reverse order view of the elements contained in this set.

Below programs illustrate the descendingSet() method in Java:

Program 1: NavigableSet with integer elements.




// A Java program to demonstrate
// descendingSet() method of NavigableSet
  
import java.util.NavigableSet;
import java.util.TreeSet;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
        NavigableSet<Integer> ns = new TreeSet<>();
        ns.add(0);
        ns.add(1);
        ns.add(2);
        ns.add(3);
        ns.add(4);
        ns.add(5);
        ns.add(6);
  
        NavigableSet new_ns = ns.descendingSet();
  
        Iterator itr = new_ns.iterator();
  
        // Iterate over the elements using itr
        while (itr.hasNext()) {
            System.out.println("Value: " + itr.next() + " ");
        }
    }
}


Output:

Value: 6 
Value: 5 
Value: 4 
Value: 3 
Value: 2 
Value: 1 
Value: 0

Program 2: NavigableSet with string elements.




// A Java program to illustrate descendingSet()
// method of NavigableSet
import java.util.NavigableSet;
import java.util.TreeSet;
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
        NavigableSet<String> ns = new TreeSet<>();
        ns.add("A");
        ns.add("B");
        ns.add("C");
        ns.add("D");
        ns.add("E");
        ns.add("F");
        ns.add("G");
  
        NavigableSet new_ns = ns.descendingSet();
  
        Iterator itr = new_ns.iterator();
  
        // Iterate over the elements using itr
        while (itr.hasNext()) {
            System.out.println("Value: " + itr.next() + " ");
        }
    }
}


Output:

Value: G 
Value: F 
Value: E 
Value: D 
Value: C 
Value: B 
Value: A

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/NavigableSet.html#descendingSet()

RELATED ARTICLES

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6781 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11995 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7164 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS