Sort Map in Java by reverse ordering of its keys
This post will discuss various methods to sort map in Java according to the reverse ordering of its keys.
1. Using TreeMap
TreeMap is a Red-Black tree-based implementation of Map, which is sorted according to the comparator provided to its constructor. By passing any Reverse Order Comparator to the TreeMap, we can sort the map according to the reverse ordering of its keys.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; class Main { // Generic method to sort map in Java by the reverse ordering of its keys public static <K extends Comparable, V> Map<K, V> sortByKeys(Map<K, V> map) { Map<K, V> treeMap = new TreeMap<>(new Comparator<K>() { @Override public int compare(K a, K b) { return b.compareTo(a); } }); treeMap.putAll(map); return treeMap; } public static void main(String[] args) { Map<String, String> colors = new HashMap<>(); colors.put("RED", "#FF0000"); colors.put("BLUE", "#0000FF"); colors.put("GREEN", "#008000"); colors.put("YELLOW", "#FFFF00"); colors = sortByKeys(colors); System.out.println("Sorted map by keys in Reverse Order:\n" + colors); } } |
Output:
Sorted map by keys in Reverse Order :
{YELLOW=#FFFF00, RED=#FF0000, GREEN=#008000, BLUE=#0000FF}
The above code uses a custom comparator, but we can use reverse order comparators provided by Java such as:
|
1 |
Map<K, V> treeMap = new TreeMap<>(Collections.reverseOrder()); |
|
1 |
Map<K, V> treeMap = new TreeMap<>((a, b) -> b.compareTo(a)); |
⮚ TreeMap.descendingMap() method
We can use TreeMap.descendingMap() that returns a reverse order view of the mappings contained in the treemap.
|
1 2 3 4 5 6 7 |
// Generic method to sort map by keys in reverse order public static <K, V> Map<K, V> sortByKeys(Map<K, V> unsortedMap) { // construct a `TreeMap` from the given map and return a reverse order // view of the mappings contained in this map return new TreeMap<>(unsortedMap).descendingMap(); } |
⮚ Using Guava’s TreeMap
We can also use the TreeMap implementation provided by Guava, as shown below:
|
1 2 3 4 5 6 7 8 |
// Generic method to sort map in Java by the reverse ordering of its keys public static <K, V> TreeMap<K, V> sortByKeys(Map<K, V> map) { TreeMap<K, V> treeMap = Maps.newTreeMap( (Comparator<K>) Ordering.natural().reverse()); treeMap.putAll(map); return treeMap; } |
2. Using LinkedHashMap
We know that the LinkedHashMap iteration order is the same as the insertion order of keys into the map. We can use this property to produce a copy of a map that is sorted according to the reverse ordering of its keys.
The idea is to create a list of keys from the map and sort it in descending order. Then for every key in the reverse sorted list, we insert a key-value pair into an empty LinkedHashMap. The resultant LinkedHashMap will be sorted according to the reverse ordering of its keys.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import java.util.*; class Main { // Generic method to sort map in Java by the reverse ordering of its keys public static <K extends Comparable, V> Map<K, V> sortByKeys(Map<K, V> map) { // create a list of map keys and sort it List<K> keys = new ArrayList<K>(map.keySet()); Collections.sort(keys, Collections.reverseOrder()); // create an empty `LinkedHashMap` Map<K, V> linkedHashMap = new LinkedHashMap<>(); // use `ListIterator` to iterate list ListIterator<K> itr = keys.listIterator(); // for every key in the sorted list, insert key-value pair // in `LinkedHashMap` while (itr.hasNext()) { K key = itr.next(); linkedHashMap.put(key, map.get(key)); } return linkedHashMap; } public static void main(String[] args) { Map<String, String> colors = new HashMap<>(); colors.put("RED", "#FF0000"); colors.put("BLUE", "#0000FF"); colors.put("GREEN", "#008000"); colors.put("YELLOW", "#FFFF00"); colors = sortByKeys(colors); System.out.println("Sorted map by keys in Reverse Order:\n" + colors); } } |
Output:
Sorted map by keys in Reverse Order :
{YELLOW=#FFFF00, RED=#FF0000, GREEN=#008000, BLUE=#0000FF}
3. Using Java 8
We can also use Java 8 Stream to sort map by keys in reverse order. Following are the steps:
- Obtain stream from the set view of the mappings contained in the map.
- Sort the stream in reverse order of keys using
Stream.sorted()method. - Construct a
LinkedHashMapfrom the stream usingStream.collect()withCollectors.toMap().
The following program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; class Main { public static void main(String[] args) { Map<String, String> colors = new HashMap<>(); colors.put("RED", "#FF0000"); colors.put("BLUE", "#0000FF"); colors.put("GREEN", "#008000"); colors.put("YELLOW", "#FFFF00"); // Sort map in Java 8 and above by reverse ordering of its keys colors = colors.entrySet() // Set<Entry<String, String>> .stream() // Stream<Entry<String, String>> .sorted(Collections.reverseOrder(Map.Entry.comparingByKey())) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new )); System.out.println("Sorted map by keys :\n" + colors); } } |
Output:
Sorted map by keys in Reverse Order :
{YELLOW=#FFFF00, RED=#FF0000, GREEN=#008000, BLUE=#0000FF}
Another approach that doesn’t involve using a collector is to use the Stream.forEachOrdered() method on the reverse sorted stream that inserts each element of the stream into a new LinkedHashMap.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; class Main { public static void main(String[] args) { Map<String, String> colors = new HashMap<>(); colors.put("RED", "#FF0000"); colors.put("BLUE", "#0000FF"); colors.put("GREEN", "#008000"); colors.put("YELLOW", "#FFFF00"); // Sort map in Java 8 and above by reverse ordering of its keys Map<String, String> sortedMap = new LinkedHashMap<>(); colors.entrySet() // Set<Entry<String, String>> .stream() // Stream<Entry<String, String>> .sorted(Collections.reverseOrder(Map.Entry.comparingByKey())) .forEachOrdered(entry -> sortedMap.put(entry.getKey(), entry.getValue())); System.out.println("Sorted map by keys :\n" + sortedMap); } } |
Output:
Sorted map by keys in Reverse Order :
{YELLOW=#FFFF00, RED=#FF0000, GREEN=#008000, BLUE=#0000FF}
That’s all about sorting Map in Java by the reverse ordering of its keys.
References:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)