How to Sort a Map by Keys in Java - Step by Step Examples



How to Sort a Map by Keys in Java ?

Answer

To sort a map by keys in Java, you can use a `TreeMap`, which automatically sorts the keys, or convert the map entries to a list, sort the list, and then convert it back to a map. This method provides a way to ensure the map is sorted by keys.



✐ Examples

1 Sorting a Map by Keys Using TreeMap

We can sort a map by keys in Java by using a `TreeMap`, which automatically sorts the keys.

For example,

  1. We start by importing the java.util.HashMap and java.util.TreeMap classes, which provide the necessary functions and data structures for working with maps.
  2. We declare and initialize a `HashMap` named unsortedMap with some key-value pairs. In this example, the map has integer keys and string values.
  3. We create a `TreeMap` named sortedMap and pass the `unsortedMap` to it, which automatically sorts the keys.
  4. We print the sorted map to the console using the `System.out.println` function to verify the sorting.

Java Program

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        // Declare and initialize an unsorted map
        Map<Integer, String> unsortedMap = new HashMap<>();
        unsortedMap.put(3, "three");
        unsortedMap.put(1, "one");
        unsortedMap.put(2, "two");

        // Create a TreeMap to sort the keys
        Map<Integer, String> sortedMap = new TreeMap<>(unsortedMap);

        // Print the sorted map
        System.out.println("Sorted Map by Keys: " + sortedMap);
    }
}

Output

Sorted Map by Keys: {1=one, 2=two, 3=three}

2 Sorting a Map by Keys Using List Conversion

We can sort a map by keys in Java by converting the map entries to a list, sorting the list, and then converting it back to a map.

For example,

  1. We start by importing the java.util.HashMap, java.util.List, java.util.Map, java.util.stream.Collectors, and java.util.LinkedHashMap classes, which provide the necessary functions and data structures for working with maps and lists.
  2. We declare and initialize a `HashMap` named unsortedMap with some key-value pairs. In this example, the map has integer keys and string values.
  3. We convert the map entries to a list and sort the list based on the keys using streams.
  4. We create a new `LinkedHashMap` from the sorted list of map entries.
  5. We print the sorted map to the console using the `System.out.println` function to verify the sorting.

Java Program

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        // Declare and initialize an unsorted map
        Map<Integer, String> unsortedMap = new HashMap<>();
        unsortedMap.put(3, "three");
        unsortedMap.put(1, "one");
        unsortedMap.put(2, "two");

        // Convert the map entries to a list and sort the list by keys
        List<Map.Entry<Integer, String>> sortedEntries = unsortedMap.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByKey())
            .collect(Collectors.toList());

        // Create a new map from the sorted list of map entries
        Map<Integer, String> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<Integer, String> entry : sortedEntries) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        // Print the sorted map
        System.out.println("Sorted Map by Keys: " + sortedMap);
    }
}

Output

Sorted Map by Keys: {1=one, 2=two, 3=three}

3 Sorting a Map by Keys in Descending Order

We can sort a map by keys in descending order in Java by using a `TreeMap` with a custom comparator.

For example,

  1. We start by importing the java.util.HashMap, java.util.Map, and java.util.TreeMap classes, which provide the necessary functions and data structures for working with maps and comparators.
  2. We declare and initialize a `HashMap` named unsortedMap with some key-value pairs. In this example, the map has integer keys and string values.
  3. We create a `TreeMap` named sortedMap with a custom comparator to sort the keys in descending order, and pass the `unsortedMap` to it.
  4. We print the sorted map to the console using the `System.out.println` function to verify the sorting.

Java Program

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        // Declare and initialize an unsorted map
        Map<Integer, String> unsortedMap = new HashMap<>();
        unsortedMap.put(3, "three");
        unsortedMap.put(1, "one");
        unsortedMap.put(2, "two");

        // Create a TreeMap with a custom comparator for descending order
        Map<Integer, String> sortedMap = new TreeMap<>(Comparator.reverseOrder());
        sortedMap.putAll(unsortedMap);

        // Print the sorted map
        System.out.println("Sorted Map by Keys (Descending): " + sortedMap);
    }
}

Output

Sorted Map by Keys (Descending): {3=three, 2=two, 1=one}

Summary

In this tutorial, we learned How to Sort a Map by Keys in Java language with well detailed examples.




More Java Maps Tutorials

  1. How to create an Empty Map in Java ?
  2. How to create a Map with Initial Key-Value Pairs in Java ?
  3. How to Print a Map in Java ?
  4. How to Add a Key-Value Pair to a Map in Java ?
  5. How to Set a Default Value for a Key in a Map in Java ?
  6. How to Update the Value for a Key in a Map in Java ?
  7. How to Check if a Map is Empty in Java ?
  8. How to Check if a Key Exists in a Map in Java ?
  9. How to Check if a Value Exists in a Map in Java ?
  10. How to Get the Value Associated with a Key in a Map in Java ?
  11. How to Remove a Key-Value Pair from a Map in Java ?
  12. How to Remove Key-Value Pairs from a Map Based on Values in Java ?
  13. How to Clear All Key-Value Pairs from a Map in Java ?
  14. How to Iterate Over Keys in a Map in Java ?
  15. How to Iterate Over Values in a Map in Java ?
  16. How to Iterate Over Entries (Key-Value Pairs) in a Map in Java ?
  17. How to Get the Size (Number of Key-Value Pairs) of a Map in Java ?
  18. How to Convert a Map to an Array of Keys in Java ?
  19. How to Convert a Map to an Array of Values in Java ?
  20. How to Merge Two Maps in Java ?
  21. How to Copy a Map in Java ?
  22. How to Check if Two Maps are Equal in Java ?
  23. How to Sort a Map by Keys in Java ?
  24. How to Sort a Map by Values in Java ?
  25. How to Filter a Map Based on Keys in Java ?
  26. How to Filter a Map Based on Values in Java ?
  27. How to Reduce Values in a Map to a Single Value in Java ?
  28. How to Convert an Array of Key-Value Pairs to a Map in Java ?
  29. How to Convert a Map to a JSON String in Java ?
  30. How to Convert a JSON String to a Map in Java ?
  31. How to Swap Keys and Values in a Map in Java ?
  32. How to Create a Map of Maps in Java ?
  33. How to Iterate Over a Map of Maps in Java ?