# How to sort a Map in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 10, 2019, updated Feb 18, 2020. Topics: Java.
Canonical URL: https://attacomsian.com/blog/how-to-sort-a-map-in-java

> Learn how to sort a Map by keys or by values in Java using Java 8 Streams. 

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:

1. Convert a Map into a Stream object
2. Sort it by using Streams' `sorted()` method
3. 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:

```java
// 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:

```plaintext
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 a `HashMap`. The `HashMap` class does not provide any ordering guarantee. If we convert the sorted stream back to the `HashMap`, 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:

```java
// 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:

```java
// 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:

```java
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:

```java
// 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:

```java
// 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:

```plaintext
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](https://attacomsian.com/blog/sort-list-using-stream-sorted-method-java)
