Sorting a Map by Keys in Java

Simple quick-to-use examples to sort a Map by keys, using TreeMap and Stream APIs, in ascending and descending (reverse) orders.

1. Using TreeMap

1.1. 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.

Map<String, Integer> unSortedMap = getUnSortedMapFromSource();
     

 
Map<String, Integer> sortedMap = new TreeMap<String, Integer>(unSortedMap);

1.2. Descending Order

To reverse sort map entries, pass Collections.reverseOrder() in TreeMap constructor.

Map<String, Integer> unSortedMap = getUnSortedMapFromSource();

Map<String, Integer> reverseSortedMap 
  = new TreeMap<String, Integer>(Collections.reverseOrder());

reverseSortedMap.putAll(unSortedMap);

2. Using Stream APIs

Since Java 8, Map.Entry class has a 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, we can pass a custom Comparator to use in sorting. This can be used to sort the map in reverse order.

2.1. Ascending Order

The Map.Entry.comparingByKey() returns a Comparator that compares Map.Entry in natural order on key.

Map<String, Integer> unSortedMap = getUnSortedMap();

//LinkedHashMap preserve the ordering of elements in which they are inserted
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();

unSortedMap.entrySet()
  .stream()
  .sorted(Map.Entry.comparingByKey())
  .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));

2.2. Descending Order

Use Comparator.reverseOrder() along with Map.Entry.comparingByKey() to reverse the ordering of the Map.Entry elements.

Map<String, Integer> unSortedMap = getUnSortedMap();

//LinkedHashMap preserve the ordering of elements in which they are inserted
LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();

//Use Comparator.reverseOrder() for reverse ordering
unSortedMap.entrySet()
  .stream()
  .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
  .forEachOrdered(x -&gt; reverseSortedMap.put(x.getKey(), x.getValue()));

3. Complete Example

The complete code used in this example, for your reference.

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
 
public class MapSortingExamples {
 
  public static void main(String[] args) {
     
    System.out.println("Sorting using TreeMap\n");
     
    sortByKeyUsingTreeMap();
 
    System.out.println("\nSorting using Java8 streams\n");
     
    sortByKeyJava8Stream();
  }
 
  private static void sortByKeyUsingTreeMap() 
  {
    Map<String, Integer> unSortedMap = getUnSortedMap();
     
    System.out.println("Unsorted Map : " + unSortedMap);
 
    Map<String, Integer> sortedMap = new TreeMap<String, Integer>(unSortedMap);
     
    System.out.println("Sorted Map   : " + sortedMap);
     
    Map<String, Integer> reverseSortedMap = new TreeMap<String, Integer>(Collections.reverseOrder());
    reverseSortedMap.putAll(unSortedMap);
     
    System.out.println("Reverse Sorted Map   : " + reverseSortedMap);
  }
 
  private static void sortByKeyJava8Stream() 
  {
    Map<String, Integer> unSortedMap = getUnSortedMap();
     
    System.out.println("Unsorted Map : " + unSortedMap);
 
    LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
    unSortedMap.entrySet().stream().sorted(Map.Entry.comparingByKey())
        .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
     
    System.out.println("Sorted Map   : " + sortedMap);
     
    LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();
    unSortedMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
        .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));
     
    System.out.println("Reverse Sorted Map   : " + reverseSortedMap);
  }
 
  private static Map<String, Integer> getUnSortedMap() 
  {
    Map<String, Integer> unsortMap = new HashMap<>();
    unsortMap.put("alex", 1);
    unsortMap.put("david", 2);
    unsortMap.put("elle", 3);
    unsortMap.put("charles", 4);
    unsortMap.put("brian", 5);
    return unsortMap;
  }
}
 
Output:
 
Sorting using TreeMap
 
Unsorted Map    : {alex=1, charles=4, david=2, brian=5, elle=3}
Sorted Map      : {alex=1, brian=5, charles=4, david=2, elle=3}
Reverse Sorted Map  : {elle=3, david=2, charles=4, brian=5, alex=1}
 
Sorting using Java8 streams
 
Unsorted Map    : {alex=1, charles=4, david=2, brian=5, elle=3}
Sorted Map      : {alex=1, brian=5, charles=4, david=2, elle=3}
Reverse Sorted Map  : {elle=3, david=2, charles=4, brian=5, alex=1}

Happy Learning !!

Leave a Reply

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial