Sort a Map by Key in java

1. Introduction

Sorting a Map by its keys is a frequently needed operation in Java. With the advent of Java 8, the Stream API introduced a new approach to processing collections, including sorting operations. This blog post will explore two methods to sort a Map by its keys in Java: using a TreeMap for natural ordering and leveraging the Java 8 Stream API for more flexibility and control over the sorting process.

2. Program Steps

1. Create and populate a HashMap with unsorted key-value pairs.

2. Sort the Map by its keys using a TreeMap to achieve natural ordering.

3. Sort the Map by its keys using the Java 8 Stream API and collect the result in a LinkedHashMap to maintain the sorted order.

4. Display the original Map, the Map sorted by TreeMap, and the Map sorted using the Stream API.

3. Code Program

import java.util.*;

public class SortMapByKeyJava8 {
    public static void main(String[] args) {
        // Creating and populating a HashMap
        Map<Integer, String> unsortedMap = new HashMap<>();
        unsortedMap.put(5, "Five");
        unsortedMap.put(1, "One");
        unsortedMap.put(3, "Three");
        unsortedMap.put(4, "Four");
        unsortedMap.put(2, "Two");

        // Displaying the original unsorted map
        System.out.println("Original map: " + unsortedMap);

        // Method 1: Sorting the map by keys using TreeMap
        Map<Integer, String> sortedMapUsingTreeMap = new TreeMap<>(unsortedMap);
        System.out.println("Map sorted by keys using TreeMap: " + sortedMapUsingTreeMap);

        // Method 2: Sorting the map by keys using Java 8 Stream API
        Map<Integer, String> sortedMapUsingStream = unsortedMap.entrySet().stream()
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));

        // Displaying the map sorted by keys using Stream API
        System.out.println("Map sorted by keys using Stream API: " + sortedMapUsingStream);


Original map: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
Map sorted by keys using TreeMap: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}
Map sorted by keys using Stream API: {1=One, 2=Two, 3=Three, 4=Four, 5=Five}


1. The program begins by creating a HashMap named unsortedMap and populating it with integer keys and string values. The insertion order in HashMap is not maintained.

2. The first method for sorting uses a TreeMapTreeMap automatically sorts by the natural ordering of its keys. The entire unsortedMap is passed to the TreeMap constructor, resulting in a new map (sortedMapUsingTreeMap) where entries are sorted by key.

3. The second method leverages the Java 8 Stream API. The unsortedMap.entrySet().stream() creates a stream of map entries, which is then sorted by keys using Map.Entry.comparingByKey(). The sorted stream is collected into a LinkedHashMap (sortedMapUsingStream) by Collectors.toMap(). Using LinkedHashMap is crucial here as it maintains the order of elements as they are inserted, preserving the sorted order.

4. The original map and the maps sorted by both methods are printed to the console, illustrating that they are sorted by keys.

5. This example demonstrates two approaches to sorting a Map by keys in Java, highlighting the traditional TreeMap method and the flexible Stream API method introduced in Java 8.