By default TreeMap elements in Java are sorted in ascending order of keys. However, we can create the TreeMap in reverse order using Collections.reverseOrder() method in Java and display the elements in descending order of keys.
The Collections.reverseOrderS() method in Java returns a Comparator that imposes reverse order of a passed Comparator object. We can use this method to sort any list or any other collection in reverse order of user defined Comparator.
// Insert elements to the TreeMap Input : treemap.put("1", "Welcome"); treemap.put("2", "to"); treemap.put("3", "the"); treemap.put("4", "Geeks"); treemap.put("5", "Community"); // Elements should be printed in reverse order // of their insertion Output : 5: Community 4: Geeks 3: the 2: to 1: Welcome
Below program shows how to traverse a TreeMap in reverse order:
5: Community 4: Geeks 3: the 2: to 1: Welcome
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.