Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
Last Updated :
30 Oct, 2017
There are two variants of descending() in Java.util.TreeMap, both are discussed in this article.
1. descendingKeySet(): It returns a reverse order Navigable Set view of the keys contained in the map.
Syntax :
public NavigableSet descendingKeySet()
Parameters:
NA
Return Value:
It returns a reverse order navigable set view of the keys in this map.
Exception:
NA
import java.io.*;
import java.util.*;
public class descendingKeySet1 {
public static void main(String[] args)
{
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
treemap.put(2, "two");
treemap.put(0, "zero");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(9, "nine");
treemap.put(7, "seven");
NavigableSet set1 = treemap.descendingKeySet();
System.out.println("Navigable set values are: " + set1);
}
}
|
Output:
Navigable set values are: [9, 7, 6, 3, 2, 0]
2. descendingMap() : It returns a reverse order view of the mappings contained in the map.
Syntax :
public NavigableMap descendingMap()
Parameters:
NA
Return Value
It returns a reverse order view of the map.
Exception:
NA
import java.io.*;
import java.util.*;
public class descendingMap {
public static void main(String[] args)
{
TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
treemap.put(2, "two");
treemap.put(0, "zero");
treemap.put(3, "three");
treemap.put(6, "six");
treemap.put(9, "nine");
treemap.put(7, "seven");
NavigableMap map1 = treemap.descendingMap();
System.out.println("Navigable map values are: " + map1);
}
}
|
Output:
Navigable map values are: {9=nine, 7=seven, 6=six, 3=three, 2=two, 0=zero}
Practical Application : There are many applications possible of descending functions explained in this article. Some among them are priority scheduling, or designing a ranking system. Latter one is demonstrated in the code below.
import java.io.*;
import java.util.*;
public class descendingAppli {
public static void main(String[] args)
{
TreeMap<Integer, String> participants = new TreeMap<Integer, String>();
participants.put(30, "Ashty");
participants.put(45, "Shavi");
participants.put(16, "Vaish");
participants.put(15, "Kil");
participants.put(11, "Manju");
NavigableMap<Integer, String> Ranks = participants.descendingMap();
System.out.println("The ranks according to scores are : ");
int count = 0;
for (NavigableMap.Entry<Integer, String> entry : Ranks.entrySet()) {
count++;
String str = Integer.toString(count);
System.out.println("Rank " + str + ": " + entry.getValue());
}
}
}
|
Output:
The ranks according to scores are :
Rank 1: Shavi
Rank 2: Ashty
Rank 3: Vaish
Rank 4: Kil
Rank 5: Manju
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...