Skip to main content

How to sort HashMap by key and value in Java

How to Sort HashMap by key and value in Java

In this article, we are going to have look at how to sort HashMap by key and how to sort HashMap by value in Java. We are going to learn different approaches to sort HashMap.

HashMap does not sort its key-value pair and also it does not maintain any order (neither insertion nor sorted). If we want to sort HashMap then we need to provide custom logic that can sort HashMap and To sort HashMap by key we can use either TreeMap or LinkedHashMap but in case of sort HashMap by value, we have the only option of LinkedHashMap as TreeMap cannot be used to sort HashMap by value.

Content of the article


How to sort HashMap by key using TreeMap in Java

To sort HashMap by key, we can use TreeMap class. TreeMap in java is used store key-value pairs and sort all the pairs w.r.t. keys. We can create a TreeMap from the HashMap and TreeMap sort HashMap by key.

Steps to sort HashMap by key using TreeMap

  • Create a Comparator, which provides logic to sort HashMap by key.
  • Create a TreeMap using Comparator.
  • Add all the entries of HashMap into the TreeMap
Let's understand this with an example:

Java Sort HashMap Example 1: Create a HashMap of Name of the Book (String) as key and its price (Integer) as value and sort into the alphabetically ascending order w.r.t. the Name of the Book (keys).

HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Programming In Java", 450);
hashMap.put("Introduction to Algorithms", 800);
hashMap.put("Data Structures", 600);
hashMap.put("Learn C++", 350);

System.out.println("-----------Before Sorting--------------");
Set<Entry<String, Integer>> unsortedEntrySet = hashMap.entrySet();
for (Entry<String, Integer> entry : unsortedEntrySet) {
      System.out.println(entry.getKey() + " = " + entry.getValue());
}

// Step 1: Create a Comparator, which provides logic to sort HashMap by key.
Comparator<String> keyComparator = (s1, s2) -> s1.compareTo(s2);

// Step 2: Create a TreeMap using Comparator.
TreeMap<String, Integer> treeMap = new TreeMap<>(keyComparator);

// Step 3: Add all the entries of HashMap into the TreeMap
treeMap.putAll(hashMap);

System.out.println("-----------After Sorting---------------");
Set<Entry<String, Integer>> sortedEntrySet = treeMap.entrySet();
for (Entry<String, Integer> entry : sortedEntrySet) {
      System.out.println(entry.getKey() + " = " + entry.getValue());
}
Output
-----------Before Sorting--------------
Programming In Java = 450
Introduction to Algorithms = 800
Data Structures = 600
Learn C++ = 350
-----------After Sorting---------------
Data Structures = 600
Introduction to Algorithms = 800
Learn C++ = 350
Programming In Java = 450

How to create an object of Comparator?

To create an object of Comparator, we have two options using Anonymous class and Lambda Expression.
Using Anonymous class
Comparator<String> keyComparator = new Comparator<String>() {
     @Override
     public int compare(String o1, String o2) {
          return o1.compareTo(o2);
     }
};
Using Lambda Expression
Comparator<String> keyComparator = (o1, o2) -> o1.compareTo(o2);
To know more about the Lambda Expression, read this article: Lambda Expression in java

How to sort HashMap by key using LinkedHashMap in Java

In the above section, we get a close look at how to sort HashMap by key using TreeMap. Now, what would happen if we do not want to use TreeMap to sort HashMap? To answer this, we have another option known as LinkedHashMap.

Why LinkedHashMap?

TreeMap is the only way to store key-value pairs in the sorted order (except SortedMap and NavigableMap but these both are the Interfaces and TreeMap is the implementation of these interfaces).
But if we do not want to use TreeMap then we need to write custom logic to sort HashMap and store the sorted order of the key-value pairs into the map who can maintain insertion order. LinkedHashMap is a Map that maintains insertion order, that's why LinkedHashMap is the other option to sort HashMap.

Steps to sort HashMap by key using LinkedHashMap

  • Fetch the entry set from the HashMap.
  • Create an ArrayList from the entrySet.
  • Create a Comparator, which provides logic to sort HashMap by key.
  • Sort the ArrayList using Comparator.
  • Create a LinkedHashMap.
  • Add all the entries of Sorted ArrayList into the LinkedHashMap.
Let's understand this with an example:

Java Sort HashMap Example 2: Create a HashMap of Name of the Book (String) as key and its price (Integer) as value and sort into the alphabetically ascending order w.r.t. the Name of the Book (keys) using LinkedHashMap.

HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Programming In Java", 450);
hashMap.put("Introduction to Algorithms", 800);
hashMap.put("Data Structures", 600);
hashMap.put("Learn C++", 350);

// Step 1: Fetch the entry set from the HashMap.
Set<Entry<String, Integer>> unsortedEntrySet = hashMap.entrySet();

System.out.println("-----------Before Sorting--------------");
for (Entry<String, Integer> entry : unsortedEntrySet) {
     System.out.println(entry.getKey() + " = " + entry.getValue());
}

// Step 2: Create an ArrayList from the entrySet.
ArrayList<Entry<String, Integer>> enrtyList = new ArrayList<>(unsortedEntrySet);

// Step 3: Create a Comparator, which provides logic to sort HashMap by key.
Comparator<Entry<String, Integer>> keyComparator 
              = (entry1, entry2) -> entry1.getKey().compareTo(entry2.getKey());

// Step 4: Sort the ArrayList using Comparator.
Collections.sort(enrtyList, keyComparator);

// Step 5: Create a LinkedHashMap.
LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();

// Step 6: Add all the entries of Sorted ArrayList into the LinkedHashMap
for (Entry<String, Integer> entry : enrtyList) {
     linkedHashMap.put(entry.getKey(), entry.getValue());
}

System.out.println("-----------After Sorting---------------");
Set<Entry<String, Integer>> sortedEntrySet = linkedHashMap.entrySet();
for (Entry<String, Integer> entry : sortedEntrySet) {
     System.out.println(entry.getKey() + " = " + entry.getValue());
}
Output
-----------Before Sorting--------------
Programming In Java = 450
Introduction to Algorithms = 800
Data Structures = 600
Learn C++ = 350
-----------After Sorting---------------
Data Structures = 600
Introduction to Algorithms = 800
Learn C++ = 350
Programming In Java = 450
To know more about how to sort arraylist in java, visit this article : How to sort ArrayList in Java.

How to sort HashMap by value using LinkedHashMap in Java

Till now, we learned how to sort HashMap by key. Now, let's have a look at how to sort HashMap by value. To sort HashMap by value, we cannot use TreeMap as TreeMap can only sort HashMap by key, not by value. Therefore, we have the only option of LinkedHashMap to sort HashMap by value.

Steps to sort HashMap by value using LinkedHashMap

  • Fetch the entry set from the HashMap.
  • Create an ArrayList from the entrySet.
  • Create a Comparator, which provides logic to sort HashMap by value.
  • Sort the ArrayList using Comparator.
  • Create a LinkedHashMap.
  • Add all the entries of Sorted ArrayList into the LinkedHashMap.
The steps to sort HashMap by value is the same as to sort HashMap by key, we just need to change the definition of Comparator. For Example:

Java Sort HashMap Example 3: Create a HashMap of Name of the Book (String) as key and its price (Integer) as value and sort HashMap by value i.e., into the ascending order w.r.t. the Price of the Book (keys) using LinkedHashMap.

HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Programming In Java", 450);
hashMap.put("Introduction to Algorithms", 800);
hashMap.put("Data Structures", 600);
hashMap.put("Learn C++", 350);

// Step 1: Fetch the entry set from the HashMap.
Set<Entry<String, Integer>> unsortedEntrySet = hashMap.entrySet();

System.out.println("-----------Before Sorting--------------");
for (Entry<String, Integer> entry : unsortedEntrySet) {
     System.out.println(entry.getKey() + " = " + entry.getValue());
}

// Step 2: Create an ArrayList from the entrySet.
ArrayList<Entry<String, Integer>> enrtyList = new ArrayList<>(unsortedEntrySet);

// Step 3: Create a Comparator, which provides logic to sort HashMap by value.
Comparator<Entry<String, Integer>> valueComparator 
              = (entry1, entry2) -> entry1.getValue().compareTo(entry2.getValue());

// Step 4: Sort the ArrayList using Comparator.
Collections.sort(enrtyList, valueComparator);

// Step 5: Create a LinkedHashMap.
LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();

// Step 6: Add all the entries of Sorted ArrayList into the LinkedHashMap
for (Entry<String, Integer> entry : enrtyList) {
     linkedHashMap.put(entry.getKey(), entry.getValue());
}

System.out.println("-----------After Sorting---------------");
Set<Entry<String, Integer>> sortedEntrySet = linkedHashMap.entrySet();
for (Entry<String, Integer> entry : sortedEntrySet) {
     System.out.println(entry.getKey() + " = " + entry.getValue());
}
Output
-----------Before Sorting--------------
Programming In Java = 450
Introduction to Algorithms = 800
Data Structures = 600
Learn C++ = 350
-----------After Sorting---------------
Learn C++ = 350
Programming In Java = 450
Data Structures = 600
Introduction to Algorithms = 800
As we can see, the HashMap is now sorted into ascending order w.r.t. the price of the book i.e., by values.

How to sort HashMap by value in descending order

To sort HashMap by value in descending order, we just need to create the reverse order Comparator. To do this, we can use Collections.reverseOrder() method.
Collections.reverseOrder() method
Comparator<T> reverseOrder(Comparator<T> comparator)
This method takes an argument of the Comparator and returns the Comparator which provides the reverse order for sorting.

Java Sort HashMap Example 4: Create a HashMap of Name of the Book (String) as key and its price (Integer) as value and sort HashMap by value in desecending order w.r.t. to the Price.

HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Programming In Java", 450);
hashMap.put("Introduction to Algorithms", 800);
hashMap.put("Data Structures", 600);
hashMap.put("Learn C++", 350);

// Step 1: Fetch the entry set from the HashMap.
Set<Entry<String, Integer>> unsortedEntrySet = hashMap.entrySet();

System.out.println("-----------Before Sorting--------------");
for (Entry<String, Integer> entry : unsortedEntrySet) {
     System.out.println(entry.getKey() + " = " + entry.getValue());
}

// Step 2: Create an ArrayList from the entrySet.
ArrayList<Entry<String, Integer>> enrtyList = new ArrayList<>(unsortedEntrySet);

// Step 3: Create a Comparator, which provides logic to sort HashMap by value.
Comparator<Entry<String, Integer>> valueComparator 
              = (entry1, entry2) -> entry1.getValue().compareTo(entry2.getValue());

// Step 4: Make a reverse order Comparator.
Comparator<Entry<String, Integer>> reverseOrderValueComparator 
              = Collections.reverseOrder(valueComparator);

// Step 5: Sort the ArrayList using Comparator.
Collections.sort(enrtyList, reverseOrderValueComparator);

// Step 6: Create a LinkedHashMap.
LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();

// Step 7: Add all the entries of Sorted ArrayList into the LinkedHashMap
for (Entry<String, Integer> entry : enrtyList) {
     linkedHashMap.put(entry.getKey(), entry.getValue());
}

System.out.println("-----------After Sorting in Descending Order---------------");
Set<Entry<String, Integer>> sortedEntrySet = linkedHashMap.entrySet();
for (Entry<String, Integer> entry : sortedEntrySet) {
     System.out.println(entry.getKey() + " = " + entry.getValue());
}
Output
-----------Before Sorting--------------
Programming In Java = 450
Introduction to Algorithms = 800
Data Structures = 600
Learn C++ = 350
-----------After Sorting---------------
Introduction to Algorithms = 800
Data Structures = 600
Programming In Java = 450
Learn C++ = 350

Conclusion

In this article, we get a close look at how to sort HashMap by key using TreeMap and LinkedHashMap. Also, we learned how to sort HashMap by value in ascending and descending order.

Related Article


Comments