TreeMap descendingKeySet() Method in Java with Examples
Last Updated :
16 Nov, 2022
The descendingKeySet() method of TreeMap class returns a reverse order NavigableSet view of the keys contained within the map. The iterator of the set returns the keys in descending order.
Note: The set is backed by the map, so changes to the map are reflected within the set, and vice-versa.
Syntax:
public NavigableSet<K> descendingKeySet()
Parameters: The method does not take any parameters.
Return Value: The method returns a navigable set view of the values contained in the map.
Exception: The method does not throw any exceptions.
Example 1:
Java
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
TreeMap<Integer, String> treemap
= new TreeMap<Integer, String>();
treemap.put( 3 , "three" );
treemap.put( 1 , "one" );
treemap.put( 2 , "two" );
treemap.put( 0 , "zero" );
treemap.put( 7 , "seven" );
treemap.put( 6 , "six" );
NavigableSet set1 = treemap.descendingKeySet();
System.out.println( "Navigable set values are: "
+ set1);
}
}
|
Output:
Navigable set values are: [7, 6, 3, 2, 1, 0]
Example 2:
Java
import java.io.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
TreeMap<Integer, String> geeks
= new TreeMap<Integer, String>();
geeks.put( 1 , "Guru" );
geeks.put( 2 , "Ayush" );
geeks.put( 3 , "Devesh" );
geeks.put( 4 , "Kashish" );
System.out.println( "TreeMap values :- " + geeks);
NavigableSet nevigableSet
= geeks.descendingKeySet();
System.out.println( "Reverse key values:- "
+ navigableSet);
}
}
|
Output:
TreeMap values :- {1=Guru, 2=Ayush, 3=Devesh, 4=Kashish}
Reverse key values:- [4, 3, 2, 1]
Share your thoughts in the comments
Please Login to comment...