TreeSet descendingIterator() method in Java with Examples
The descendingIterator() method of java.util.TreeSet<E> class is used to return an iterator over the elements in this set in descending order.
Syntax:
public Iterator descendingIterator()
Return Value: This method returns an iterator over the elements in this set in descending order.
Below are the examples to illustrate the descendingIterator() method
Example 1:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
TreeSet<Integer> treeadd = new TreeSet<Integer>();
treeadd.add( 10 );
treeadd.add( 20 );
treeadd.add( 30 );
treeadd.add( 40 );
System.out.println( "TreeSet: " + treeadd);
Iterator<Integer>
iterator = treeadd.descendingIterator();
System.out.println( "\nValues using DescendingIterator:" );
while (iterator.hasNext()) {
System.out.println( "Value : "
+ iterator.next());
}
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output
TreeSet: [10, 20, 30, 40]
Values using DescendingIterator:
Value : 40
Value : 30
Value : 20
Value : 10
Example 2:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
TreeSet<String> treeadd = new TreeSet<String>();
treeadd.add( "A" );
treeadd.add( "B" );
treeadd.add( "C" );
treeadd.add( "D" );
System.out.println( "TreeSet: " + treeadd);
Iterator<String>
iterator = treeadd.descendingIterator();
System.out.println( "\nValues using DescendingIterator:" );
while (iterator.hasNext()) {
System.out.println( "Value : "
+ iterator.next());
}
}
catch (Exception e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output
TreeSet: [A, B, C, D]
Values using DescendingIterator:
Value : D
Value : C
Value : B
Value : A
Last Updated :
31 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...