It is possible to display the keys of a TreeMap in descending order but how do you sort them?
There are two solutions:
Copy TreeMap to a new TreeMap
This method consists of copying TreeMap to a new TreeMap so that you can pull the keys in descending order using descendingKeySet, you don't need to create a new TreeMap.
private static void printReverseTreeMap(TreeMaptreeMap){
for(String key : treeMap.descendingKeySet()){
System.out.println("value of " + key + " is " + treeMap.get(key));
}
}
Create a new TreeMap in descending order
You can use this method to create a new Map in descending order using descendingMap as well as Collections.reverseOrder(). descendingMap returns an object NavigableMap.
NavigableMapreveresedTreeMap = treeMap.descendingMap();
References:
https://stackoverflow.com/questions/9338209/how-to-print-treemap-in-reverse-order
Commentaires (12)
Connectez-vous pour commenter
Rejoignez la discussion et partagez vos connaissances avec la communauté
Excellent tutoriel !
N'hésitez pas si vous avez des questions.