In this short article, you will learn how to sort a Map in Java. This is probably one of the most frequently asked questions in Java interviews.
In Java, there are multiple ways to sort a Map, but we will focus on Java 8 Streams which is quite an elegant way of achieving this.
Java 8 Streams
Using Java 8 Streams, we can sort a map both by keys and by values. Here is how it works:
- Convert a Map into a Stream object
- Sort it by using Streams'
sorted()
method - Collect the entries and return them as a
LinkedHashMap
(keep the sorted order)
The sorted()
method takes a Comparator
as a parameter, making it possible to sort the map by any type of value.
Sort By Keys
Here is an example that sorts the Map by keys using Java 8 streams:
// create a map
Map<String, Integer> codes = new HashMap<>();
codes.put("United States", 1);
codes.put("Germany", 49);
codes.put("France", 33);
codes.put("China", 86);
codes.put("Pakistan", 92);
// sort the map by keys
Map<String, Integer> sorted = codes.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
// print map elements
sorted.entrySet().forEach(System.out::println);
The above program will print the following on the console:
China=86
France=33
Germany=49
Pakistan=92
United States=1
Notice the use of
LinkedHashMap
to store the sorted results to keep the order. By default,Collectors.toMap()
returns aHashMap
. TheHashMap
class does not provide any ordering guarantee. If we convert the sorted stream back to theHashMap
, we might lose the elements ordering.
If you want to sort the Map by keys in reserve order, you only need to change the comparing order to reverse like below:
// sort the map by keys in reversed order
Map<String, Integer> sorted = codes.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByKey().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
Sort By Values
Off course, you can sort a Map by its values too using the Stream API:
// create a map
Map<String, Integer> codes = new HashMap<>();
codes.put("United States", 1);
codes.put("Germany", 49);
codes.put("France", 33);
codes.put("China", 86);
codes.put("Pakistan", 92);
// sort the map by values
Map<String, Integer> sorted = codes.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
// print map elements
sorted.entrySet().forEach(System.out::println);
Here is the output that shows the Map is sorted by values:
United States=1
France=33
Germany=49
China=86
Pakistan=92
And if you want to sort the Map by values in descending order, just do the following:
// sort the map by values in reversed order
Map<String, Integer> sorted = codes.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
Using TreeMap
The TreeMap
class stores the keys in natural sorted order. It works perfect for sorting a Map by keys. All you need to do is create a TreeMap
object, and push all the existing data from the HashMap into it:
// create a map
Map<String, Integer> codes = new HashMap<>();
codes.put("United States", 1);
codes.put("Germany", 49);
codes.put("France", 33);
codes.put("China", 86);
codes.put("Pakistan", 92);
// convert `HashMap` to `TreeMap`
Map<String, Integer> sorted = new TreeMap<>(codes);
// print tree elements
sorted.entrySet().forEach(System.out::println);
Here is the output:
China=86
France=33
Germany=49
Pakistan=92
United States=1
As you can see above, the keys (countries' names) are sorted in a natural order.
Read Next: How to sort a List using Stream sorted() in Java
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.