Sort 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

Java TreeMap stores the map entries according to the natural ordering of its keys, or by a Comparator provided at map creation time. Note that TreeMap is not synchronized, so use it carefully in concurrent scenarios.

1.1. Ascending Order or Default Order

By default, all key-value pairs in TreeMap are sorted in their natural ordering. To sort Map entries in default natural order, add all entries from the unsorted Map into the TreeMap.

Map<String, Integer> unsortedMap = Map.of("a", 1, "c", 3, "b", 2, "e", 5, "d", 4);

Map<String, Integer> sortedTreeMap = new TreeMap<>(unsortedMap);

System.out.println(sortedTreeMap);

The program output.

{a=1, b=2, c=3, d=4, e=5}

1.2. Descending Order or Reverse Order

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

Map<String, Integer> unsortedMap = Map.of("a", 1, "c", 3, "b", 2, "e", 5, "d", 4);

Map<String, Integer> sortedTreeMap = new TreeMap<>(Comparator.reverseOrder());
sortedTreeMap.putAll(unsortedMap);

System.out.println(sortedTreeMap);

The program output.

{e=5, d=4, c=3, b=2, a=1}

2. Using Java Streams

Since Java 8, Map.Entry class has a static method comparingByKey(), which returns a Comparator comparing the Map entries in the natural order of keys. This Comparator can be used with Stream.sorted() method to sort the stream of Map entries.

map.entrySet()
  .stream()
  .sorted(Map.Entry.comparingByKey())
  ...

2.1. Ascending Order

The following Java program sorts the entries of a Map by keys in the natural order and collects the sorted entries in a LinkedHashMap. We are collecting the entries in LinkedHashMap because it maintains the insertion order.

Map<String, Integer> unsortedMap = Map.of("a", 1, "c", 3, "b", 2, "e", 5, "d", 4);

LinkedHashMap<String, Integer> sortedMap = unsortedMap.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByKey())
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

System.out.println(sortedMap);

The program output.

{a=1, b=2, c=3, d=4, e=5}

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 = Map.of("a", 1, "c", 3, "b", 2, "e", 5, "d", 4);

LinkedHashMap<String, Integer> sortedMap = unsortedMap.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        Map.Entry::getValue,
        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

System.out.println(sortedMap);

The program output.

{e=5, d=4, c=3, b=2, a=1}

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
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

Dark Mode

Dark Mode