Java Program to Sort map by keys

Updated on December 9, 2024
Sort map by keys header image

Introduction

Sorting a map by its keys is a common requirement when working with data in Java. This operation helps in maintaining the order and can be critical for tasks that depend on the sequence of elements. The Java platform offers various approaches to perform this task effectively, leveraging its robust API and collection framework.

In this article, you will learn how to sort a map by its keys through practical examples. Explore different methods: using the TreeMap class and employing the stream API from Java 8 upwards. Each approach will be demonstrated with clear, concise examples to ensure you can apply these techniques in your Java applications.

Using TreeMap to Sort

Basic Sorting with TreeMap

  1. Understand that TreeMap sorts keys based on their natural ordering or by a comparator provided at map creation.

  2. Create a simple HashMap and populate it with unsorted values.

  3. Initialize a TreeMap with the HashMap to automatically sort the keys.

    java
    import java.util.*;
    
    public class SortMapByKey {
        public static void main(String[] args) {
            // Creating a HashMap
            Map<String, Integer> unsortedMap = new HashMap<>();
            unsortedMap.put("Banana", 3);
            unsortedMap.put("Apple", 5);
            unsortedMap.put("Orange", 2);
            unsortedMap.put("Mango", 8);
    
            // Sorting by keys using TreeMap
            Map<String, Integer> sortedMap = new TreeMap<>(unsortedMap);
            for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
                System.out.println(entry.getKey() + " : " + entry.getValue());
            }
        }
    }
    

    Here, a HashMap is first initialized and populated with out-of-order data. A TreeMap is then used to reorder the elements by their keys. The result is displayed, showing the keys sorted alphabetically.

Using a Custom Comparator

  1. Know that you can define custom order for your keys with a Comparator.

  2. Implement a Comparator that sorts the keys in a descending order.

  3. Use this Comparator when initializing the TreeMap.

    java
    import java.util.*;
    
    public class SortByKeyWithComparator {
        public static void main(String[] args) {
            // Creating a HashMap
            Map<String, Integer> unsortedMap = new HashMap<>();
            unsortedMap.put("Banana", 3);
            unsortedMap.put("Apple", 5);
            unsortedMap.put("Orange", 2);
            unsortedMap.put("Mango", 8);
    
            // Custom Comparator for descending order
            Comparator<String> customComparator = (k1, k2) -> k2.compareTo(k1);
    
            // TreeMap with Comparator
            Map<String, Integer> sortedMap = new TreeMap<>(customComparator);
            sortedMap.putAll(unsortedMap);
    
            for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
                System.out.println(entry.getKey() + " : " + entry.getValue());
            }
        }
    }
    

    In this code, a custom Comparator is used to sort the map's keys in reverse alphabetical order. The comparator is passed to the TreeMap constructor.

Sorting Using Java Stream API

Stream Sort and Collect

  1. Utilize Java Streams to sort a HashMap based on its keys.

  2. Collect the results into a new LinkedHashMap to preserve the order.

    java
    import java.util.*;
    import java.util.stream.Collectors;
    
    public class StreamSortMap {
        public static void main(String[] args) {
            // Creating a HashMap
            Map<String, Integer> unsortedMap = new HashMap<>();
            unsortedMap.put("Banana", 3);
            unsortedMap.put("Apple", 5);
            unsortedMap.put("Orange", 2);
            unsortedMap.put("Mango", 8);
    
            // Sorting using stream
            Map<String, Integer> sortedMap = unsortedMap.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new));
    
            sortedMap.forEach((key, value) -> System.out.println(key + " : " + value));
        }
    }
    

    This example leverages the Stream API to sort the map's entries by keys and then collects them in a LinkedHashMap to maintain the sort order. The comparingByKey() method of Map.Entry is used to perform the comparison.

Conclusion

Sorting a map by its keys in Java can be accomplished using either the TreeMap or the Stream API. While TreeMap provides a straightforward, automatic sorting mechanism, the Stream API offers flexibility, especially useful when working with complex data structures or when needing to combine sorting with other operations. Apply these techniques in diverse scenarios to improve data management and application logic in your Java programs. By mastering these methods, get to enhance the structure and performance of your Java applications efficiently.