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

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…