By Lokesh Gupta | Filed Under: Java Sorting
Simple quick to use examples to sort a Map by key, using TreeMap and Stream APIs, in ascending and descending (reverse) orders.
Sort Map by Key using TreeMap
In ascending order
By default, all key-value pairs in TreeMap are sorted in their natural order. So all you need to do is add all unsorted key-value pairs in TreeMap .
In descending order
To reverse sort map entries, pass Collections.reverseOrder() in TreeMap constructor.
Sort Map by Key using Stream APIs
In java 8, Map.Entry class has static method comparingByKey() to help you in sorting by keys. This method returns a Comparator that compares Map.Entry in natural order on key.
Alternatively, you can pass a custom Comparator to use in sorting. This can be used to sort the map in reverse order.
In ascending order
In descending order
Complete Example
The complete code used in this example, for your reference.
Drop me your questions in comments section.
By Chaitanya Singh | Filed Under: Java Collections
As we know that HashMap doesn’t preserve any order by default. If there is a need we need to sort it explicitly based on the requirement. In this tutorial we will learn how to sort HashMap by keys using TreeMap and by values using Comparator.
HashMap Sorting by Keys
In this example we are sorting the HashMap based on the keys using the TreeMap collection class.
HashMap Sorting by Values
In this example we are sorting HashMap by values using Comparator.
In the last article, I have shown you how to sort a Map by values in Java 8 and in this tutorial, you will learn how to sort a Map by keys e.g. an HashMap, ConcurrentHashMap, LinkedHashmap, or even Hashtable. Theoretically, you cannot sort a Map because it doesn’t provide any ordering guarantee. For example, when you iterate over a HashMap, you don’t know in which order entries will be traversed because HashMap doesn’t provide any ordering. Then, how can you sort a Map which doesn’t support order? Well, you can’t and that’s why you only sort entries of HashMap but you don’t store the result back into HasMap or any other Map which doesn’t support ordering. If you do so, then sorting will be lost.
Here is an example of incorrect sorting. Here even after sorting the Map, we are doing the mistake of storing the result back into a Map which doesn’t provide any ordering guarantee, hence the result is an unordered map even after sorting.
Here is the output to confirm what I said:
If Map was sorted then the «clothes» should have come first ahead of «grocery» . The mistake was blindly relying on toMap() method of Collectors class. This class provides no guarantee of what kind of Map will be used to collect those elements. Since Map interface doesn’t guarantee order, they are also not bound to store element in any order.
Though, it’s easy to solve this problem because Collectors >toMap() class which allows you to instruct which kind of Map should be used to store those entries. You can use a LinkedHashMap to store mappings to preserve the sorting order because LinkedHashMap keep keys in the order they were added. Here is the modified code which sorts a Map in the order of keys:
The code passed into to toMap() method is interesting, the first parameter is used as a key, second is used as value and third is used to break ties i.e. if two entries are equal then which entries will be chosen is decided by the third parameter, here we are using the second entry. The fourth parameter is the important one, which uses a constructor reference to tell Collector that for copying a LinkedHashMap should be used. See Java SE 8 for the Really Impatient to learn more about how constructor interference is used.
Steps to sort a Map by keys in Java 8
Here are the high-level steps you can take to sort a Map e.g. HashMap, Hashtable, ConcurentHashMap or LinkedHashMap to sort them in the ascending and descending order of their keys:
1) Get all entries by calling the Map.entrySet() method
2) Get a stream of entries by calling the stream() method, which Set inherit from Collection interface.
3) Sort all entries of Stream by calling the sorted() method.
4) In order to sort them by keys, prov >sorted() method which sorts entries by keys. This can be done by calling Map.Entry.comparingKey() method returns a Comparator which compares key in their natural order.
5) Store the result of sorting in a LinkedHashMap by using the collect() method of Stream class.
6) Use Collectors.toMap() method to collect sorted entries into LinkedHashMap
Java Program to sort a Map by keys in JDK 8
Here is the complete Java program to sort Map e.g. HashMap by keys in JDK 8. In this example, you will learn to sort Map by both lambda expression and method reference. We’ll also use new classes e.g. Stream and new methods added into Map.Entry class to sort all entries by their Map and store the result into a LinkedHashMap.
You can see that initially map was not sorted but it is later sorted in the order of keys, which are a string and that’s why clothes come ahead of grocery. Similarly, when we sorted the map in the descending order, clothes come last. This proves that our sorting code is working fine.
If you want more sophistication and customization you can do that at Comparator level and you can prov >comparingKey() method, which by default compare keys in their natural order.
For example, if a key were not String but a user object e.g. a Book, then you could have sorted book by title, author or price by prov >java.util.Map.Entry >comparingKey() and comparingValue() are overloaded to accept a Comparator. You can see a good Java 8 book e.g. Java SE 8 for Really Impatient to learn more about them.

That’s all about how to sort a Map by keys in Java 8. The simplest way to achieve this is by using the sorted() method of Stream and the newly added comparingKey() method of Map.Entry >Collections.reverseOrder() method or Comparator.reversed() method of Java 8.
Related Java 8 Tutorials
If you are interested in learning more about new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
- 20 Examples of Date and Time in Java 8 (tutorial)
- How to use Stream class in Java 8 (tutorial)
- How to use filter() method in Java 8 (tutorial)
- How to use forEach() method in Java 8 (example)
- How to join String in Java 8 (example)
- How to convert List to Map in Java 8 (solution)
- How to use peek() method in Java 8 (example)
- 5 Books to Learn Java 8 from Scratch (books)
Thank for reading this article so far. If you like this tutorial then please share with your friends and colleagues. If you have any question or feedback then please drop a comment.