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.

Download  Run Code

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:

TreeMap.descendingMap() method

We can use TreeMap.descendingMap() that returns a reverse order view of the mappings contained in the treemap.

Download  Run Code

⮚ Using Guava’s TreeMap

We can also use the TreeMap implementation provided by Guava, as shown below:

Download  Run Code

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.

Download  Run Code

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:

  1. Obtain stream from the set view of the mappings contained in the map.
  2. Sort the stream in reverse order of keys using Stream.sorted() method.
  3. Construct a LinkedHashMap from the stream using Stream.collect() with Collectors.toMap().

The following program demonstrates it:

Download  Run Code

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.

Download  Run Code

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:

1. TreeMap Javadoc – Java SE 8

2. LinkedHashMap Javadoc – Java SE 8 Javadoc