Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaNavigableSet descendingIterator() method in Java

NavigableSet descendingIterator() method in Java

The descendingIterator() method of NavigableSet interface in Java is used to return an iterator over the elements in this set, in descending order. This iterator can be then used to iterate over the elements of the set.

The iterator returned by this set is also equivalent to descendingSet().iterator().

Syntax:

Iterator<E> descendingIterator()

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

Parameters: This function does not accepts any parameter.

Return Value: It returns an iterator over the set of elements contained in this set container in descending order.

Below programs illustrate the descendingIterator() method in Java:

Program 1: NavigableSet with integer elements.




// A Java program to demonstrate
// descendingIterator() 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);
  
        Iterator<Integer> itr = ns.descendingIterator();
  
        // 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 iterator()
// 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");
  
        Iterator<String> itr = ns.descendingIterator();
  
        // 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#descendingIterator()

RELATED ARTICLES

Most Popular

Recent Comments