Sort Map in Java by Reverse Ordering of its keys

In this post, we 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 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.

Java

Download   Run Code

Output:

Sorted Map by Keys in Reverse Order :
{YELLOW=#FFFF00, RED=#FF0000, GREEN=#008000, BLUE=#0000FF}

Above code uses a custom comparator but we can use reverse order comparators provided by Java such as:

 

2. TreeMap.descendingMap()

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

 

Download   Run Code

 

3. Using Guava’s TreeMap

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

Download   Run Code

 

2. Using LinkedHashMap

We know that LinkedHashMap iteration order is same as 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 key-value pair into an empty LinkedHashMap. The resultant LinkedHashMap will be sorted according to the reverse ordering of its keys.

Java

Download   Run Code

Output:

Sorted Map by Keys in Reverse Order :
{YELLOW=#FFFF00, RED=#FF0000, GREEN=#008000, BLUE=#0000FF}

 

3. Java 8

We can also use Java 8 Stream API to sort Map by keys in reverse order. Below are the steps:

  1. Obtain stream from 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().

Java

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 collector is to use Stream.forEachOrdered() method on the reverse sorted stream that inserts each element of the stream into a new LinkedHashMap.

Java

Download   Run Code

Output:

Sorted Map by Keys in Reverse Order :
{YELLOW=#FFFF00, RED=#FF0000, GREEN=#008000, BLUE=#0000FF}

 
References:

1. TreeMap Javadoc – Java SE 8

2. LinkedHashMap Javadoc – Java SE 8 Javadoc

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz