Sorting Map By Keys in Java 8 [Snippet]

In this example, we will write a Java program to sort a Map by keys in Java 8.
In Java 8, the Collectors class provide an overloaded version of toMap() class which allows you to instruct which kind of Map should be used to store those entries. In this example, we will use a LinkedHashMap to store mappings to preserve the sorting order because LinkedHashMap keeps the keys in the order they were added.

Steps to sort a Map by keys in Java 8

Here are the simple steps 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, provide a Comparator to a sorted() method which sorts entries by keys.
  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.
package net.javaguides.examples;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import static java.util.stream.Collectors.*;

import java.util.Collections;

import static java.util.Map.Entry.*;

/**
 * Java Program to sort a Map by keys in Java 8
 * @author Ramesh Fadatare
 *
 */
public class Java8SortMapExample {
    public static void main(String[] args) {

        // a Map with string keys and integer values
        Map < String, Integer > courseMap = new HashMap < > ();
        courseMap.put("C", 1);
        courseMap.put("C++", 2);
        courseMap.put("Core Java", 3);
        courseMap.put("Advance Java", 4);
        courseMap.put("Spring Framework", 5);
        courseMap.put("Hibernate Framework", 6);
        courseMap.put("Spring Boot", 7);

        System.out.println("map before sorting: " + courseMap);

        // let's sort this map by keys first
        Map < String, Integer > sorted = courseMap.entrySet()
            .stream()
            .sorted(comparingByKey())
            .collect(toMap(e - > e.getKey(), e - > e.getValue(), (e1, e2) - > e2, LinkedHashMap::new));

        // above code can be cleaned a bit by using method reference
        sorted = courseMap
            .entrySet()
            .stream()
            .sorted(comparingByKey())
            .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) - > e2, LinkedHashMap::new));

        System.out.println("sort map in ascending order : " + sorted);

        sorted = courseMap
            .entrySet()
            .stream()
            .sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
            .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) - > e2, LinkedHashMap::new));
        System.out.println("sort map in descending order: " + sorted);
    }
}
Output:
map before sorting: {C++=2, Core Java=3, Advance Java=4, C=1, Hibernate Framework=6, Spring Framework=5, Spring Boot=7}
sort map in ascending order : {Advance Java=4, C=1, C++=2, Core Java=3, Hibernate Framework=6, Spring Boot=7, Spring Framework=5}
sort map in descending order: {Spring Framework=5, Spring Boot=7, Hibernate Framework=6, Core Java=3, C++=2, C=1, Advance Java=4}

Collections Framework Examples

Comments