How to create a TreeMap in reverse order in Java
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.
Examples:
// 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:
// Java program to traverse a TreeMap // in reverse oder import java.util.*; class GFG { public static void main(String args[]) { // Map to store the elements Map<String, String> treemap = new TreeMap<String, String>(Collections.reverseOrder()); // Put elements to the map treemap.put("1", "Welcome"); treemap.put("2", "to"); treemap.put("3", "the"); treemap.put("4", "Geeks"); treemap.put("5", "Community"); Set set = treemap.entrySet(); Iterator i = set.iterator(); // Traverse map and print elements while (i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } } } |
5: Community 4: Geeks 3: the 2: to 1: Welcome
Recommended Posts:
- TreeMap in Java
- Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
- Java.util.TreeMap.containskey() and containsValue() in Java
- Java.util.TreeMap.firstEntry() and firstKey() in Java
- Java.util.TreeMap.descendingMap() and descendingKeyset() in Java
- Java.util.TreeMap.floorEntry() and floorKey() in Java
- TreeMap put() Method in Java
- HashMap and TreeMap in Java
- TreeMap get() Method in Java
- Java.util.TreeMap.put() and putAll() in Java
- TreeMap subMap() Method in Java
- TreeMap size() Method in Java
- TreeMap containsKey() Method in Java
- TreeMap clone() Method in Java
- TreeMap keySet() Method in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



