Java Program to sort a HashMap by Keys and Values


HashMap, a frequently employed data structure in the Java programming language, enables programmers to store key-value pairs. This data structure is an exceedingly efficient method for storing data and allows for swift value retrieval based on keys. However, on occasion, it may become necessary to arrange the HashMap by its keys or values. In this article, we will delve into the procedures for sorting a HashMap in Java by its keys and values, as well as examine the performance implications associated with each technique.

Time complexity and HashMap

The time complexity of the above technique for sorting a HashMap by its values is O(n log n), where n denotes the number of entries in the HashMap. This is because the process consists of generating a List of Map.Entry objects, which takes O(n) time, and then sorting the List using a Comparator, which takes O(n log n) time. Ultimately, inserting the sorted entries into a TreeMap takes O(n log n) time. Consequently, the overall time complexity of the approach is O(n log n).

Different Approaches of Sorting the HashMap

Sorting a HashMap by Keys

To arrange a HashMap based on its keys in Java, one can utilize the TreeMap class. The TreeMap is a sorted map that organizes its entries in a sorted pattern based on their natural ordering or a customized Comparator. The ensuing steps are involved in ordering a HashMap according to its keys

Construct a TreeMap instance and feed the HashMap into its constructor. The TreeMap will sort the entries automatically based on their keys.

Iterate through the TreeMap's entries utilizing a for-each loop and display them in the sorted pattern.

Example 1

The aforementioned code begins with the creation of a HashMap instance, in which key-value pairs are added. Following this, a TreeMap instance is created by feeding the aforementioned HashMap into its constructor. As a result, the TreeMap will sort the entries based on their keys. In conclusion, we loop through the TreeMap's entries with a for-each loop and present them in a sorted order.

It's essential to mention that the time complexity of sorting a HashMap by its keys utilizing this technique is O(n log n), where n represents the total number of entries in the Map. This is due to the fact that creating a TreeMap instance takes O(n log n) time, which is the same as sorting an array. As a result, sorting a HashMap by its keys using this method can be quite costly for large maps.

import java.util.*;

public class SortHashMapByKey {
   public static void main(String[] args) {
      HashMap<String, Integer> map = new HashMap<>();
      map.put("John", 80);
      map.put("Alice", 70);
      map.put("Bob", 90);
      map.put("David", 75);
      
      System.out.println("HashMap before sorting: " + map);
      
      TreeMap<String, Integer> sortedMap = new TreeMap<>(map);
      System.out.println("HashMap after sorting by keys: " + sortedMap);
      
      for(Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
         System.out.println(entry.getKey() + ": " + entry.getValue());
      }
   }
}

Output

HashMap before sorting: {Alice=70, Bob=90, David=75, John=80}
HashMap after sorting by keys: {Alice=70, Bob=90, David=75, John=80}
Alice: 70
Bob: 90
David: 75
John: 80

Sorting a HashMap by Values

Arranging a HashMap by its values is a more intricate process compared to sorting by keys. This is due to the absence of a built-in technique in Java for sorting a HashMap by its values. Nevertheless, we can accomplish this by utilizing a Comparator and a TreeMap.

To sort a HashMap by its values, we first generate a List of Map.Entry objects that mirror the entries in the HashMap. Afterward, we sort the List using a personalized Comparator that assesses the values of the Map.Entry objects. In conclusion, we insert the sorted entries into a brand new TreeMap, which will sort the entries based on their values.

Example 2

import java.util.*;

public class SortHashMapByValue {
   public static void main(String[] args) {
      // create a HashMap to be sorted by values
      Map<String, Integer> unsortedMap = new HashMap<>();
      unsortedMap.put("A", 5);
      unsortedMap.put("B", 3);
      unsortedMap.put("C", 7);
      unsortedMap.put("D", 1);

      // create a List of Map Entries
      List<Map.Entry<String, Integer>> entryList = new ArrayList<>(unsortedMap.entrySet());

      // sort the List using a Comparator
      Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
         @Override
         public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
         return o1.getValue().compareTo(o2.getValue());
         }
      });

      // insert the sorted entries into a TreeMap
      Map<String, Integer> sortedMap = new TreeMap<>();
      for (Map.Entry<String, Integer> entry : entryList) {
         sortedMap.put(entry.getKey(), entry.getValue());
      }

      // print the sorted Map
      System.out.println(sortedMap);
   }
}

Output

{D=1, B=3, A=5, C=7}

Performance Comparison: Sorting by Keys vs. Sorting by Values

Determining whether to sort a HashMap by keys or values depends on the specific scenario. Sorting by keys is usually faster than sorting by values, since it can be achieved using the built-in TreeMap.sort() method, which has a time complexity of O(n log n). In contrast, sorting by values necessitates a custom Comparator and a TreeMap, which has a greater time complexity of O(n log n).

Conclusion

Sorting a HashMap in Java can be achieved in two distinct ways: sorting by keys or by values. When the keys in the HashMap are known and unique, and the sorting is based on the values' significance, then sorting by keys is favored. On the other hand, when the sorting is primarily based on the values, and the keys' importance is secondary, then sorting by values is preferred.

Sorting by keys in Java's HashMap is a fairly straightforward process that can be accomplished using the built-in TreeMap.sort() method. In contrast, sorting by values necessitates a custom Comparator and a TreeMap. Depending on the specific requirements, either method may be favored.

Updated on: 19-Jul-2023

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements