Sorting a Hashmap according to values
Last Updated : 03 Feb, 2025
Given the marks scored out of 100 by a student in subjects where the name of the subject is key and marks scored is the value. A HashMap is created using the subject name and respective marks as key-value pairs. The task is to sort the HashMap according to values i.e. according to marks.
Example:
Input : arr[][] = [[“Math”, 98], [“Data Structure”, 85], [“Database”, 91]
[“Java”, 95], [“Operating System”, 79], [“Networking”, 80]]
Output: Operating System: 79
Networking: 80
Data Structure: 85
Database: 91
Java: 95
Math: 98
Explanation: The HashMap is sorted based on marks of each subject.
Using Auxiliary List – O(n * log(n)) Time and O(n) Space
The idea is to store the HashMap entries in an array in the form of string and integer pairs. Then fetch values and keys from the array and put them in a new HashMap.
Note: For C++, the key-value pairs in HashMap are stored in sorted order based on key, so we can’t sort the HashMap in C++.
Below is given the implementation:
C++ // C++ program to sort unordered_map by values #include <bits/stdc++.h> using namespace std; // function to sort unordered_map by values void sortByValue(unordered_map<string, int> &hm) { // Create a list from elements of unordered_map vector<pair<string, int>> list(hm.begin(), hm.end()); // Sort the list sort(list.begin(), list.end(), [](const pair<string, int> &o1, const pair<string, int> &o2) { return o1.second < o2.second; }); // put data from sorted list to unordered_map unordered_map<string, int> temp; for (auto &aa : list) { cout<<aa.first<<": "<<aa.second<<endl; } } // Driver Code int main() { unordered_map<string, int> hm; // enter data into unordered_map hm["Math"] = 98; hm["Data Structure"] = 85; hm["Database"] = 91; hm["Java"] = 95; hm["Operating System"] = 79; hm["Networking"] = 80; sortByValue(hm); return 0; }
Java // Java program to sort hashmap by values import java.util.*; import java.lang.*; class GFG { // function to sort hashmap by values static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } // Driver Code public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter data into hashmap hm.put("Math", 98); hm.put("Data Structure", 85); hm.put("Database", 91); hm.put("Java", 95); hm.put("Operating System", 79); hm.put("Networking", 80); Map<String, Integer> hm1 = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : hm1.entrySet()) { System.out.println(en.getKey() + ": " + en.getValue()); } } }
Python # Python program to sort dictionary by values # function to sort dictionary by values def sortByValue(hm): # Create a list from elements of dictionary list_ = sorted(hm.items(), key=lambda item: item[1]) # put data from sorted list to dictionary temp = {k: v for k, v in list_} return temp # Driver Code if __name__ == "__main__": hm = {} # enter data into dictionary hm["Math"] = 98 hm["Data Structure"] = 85 hm["Database"] = 91 hm["Java"] = 95 hm["Operating System"] = 79 hm["Networking"] = 80 hm1 = sortByValue(hm) # print the sorted dictionary for key, value in hm1.items(): print(f"{key}: {value}")
C# // C# program to sort Dictionary by values using System; using System.Collections.Generic; using System.Linq; class GFG { // function to sort Dictionary by values static Dictionary<string, int> sortByValue(Dictionary<string, int> hm) { // Create a list from elements of Dictionary var list = hm.ToList(); // Sort the list list.Sort((o1, o2) => o1.Value.CompareTo(o2.Value)); // put data from sorted list to Dictionary Dictionary<string, int> temp = new Dictionary<string, int>(); foreach (var aa in list) { temp[aa.Key] = aa.Value; } return temp; } // Driver Code static void Main() { Dictionary<string, int> hm = new Dictionary<string, int>(); // enter data into dictionary hm["Math"] = 98; hm["Data Structure"] = 85; hm["Database"] = 91; hm["Java"] = 95; hm["Operating System"] = 79; hm["Networking"] = 80; Dictionary<string, int> hm1 = sortByValue(hm); // print the sorted dictionary foreach (var en in hm1) { Console.WriteLine(en.Key + ": " + en.Value); } } }
JavaScript // JavaScript program to sort object by values // function to sort object by values function sortByValue(hm) { // Create a list from elements of object let list = Object.entries(hm); // Sort the list list.sort((o1, o2) => o1[1] - o2[1]); // put data from sorted list to object let temp = {}; for (let aa of list) { temp[aa[0]] = aa[1]; } return temp; } // Driver Code let hm = {}; // enter data into object hm["Math"] = 98; hm["Data Structure"] = 85; hm["Database"] = 91; hm["Java"] = 95; hm["Operating System"] = 79; hm["Networking"] = 80; let hm1 = sortByValue(hm); // print the sorted object for (let key in hm1) { console.log(key + ": " + hm1[key]); }
OutputOperating System: 79 Networking: 80 Data Structure: 85 Database: 91 Java: 95 Math: 98
Time Complexity: O(n * log(n)), required to traverse through the HashMap. Here n is the number of entries in the HashMap.
Space Complexity: O(n), required to store the key-value pairs in an auxiliary array.
Using Auxiliary List and Lambda Expression – O(n * log(n)) Time and O(n) Space
The idea is similar to the above approach, the only difference in this approach is we will be using lambda expression to sort the list.
Below is given the implementation:
Java // Java program to sort hashmap by values import java.lang.*; import java.util.*; class GFG { // function to sort hashmap by values static HashMap<String, Integer> sortByValue( HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); // Sort the list using lambda expression Collections.sort(list, (i1, i2) -> i1.getValue().compareTo(i2.getValue())); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } // Driver Code public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter data into hashmap hm.put("Math", 98); hm.put("Data Structure", 85); hm.put("Database", 91); hm.put("Java", 95); hm.put("Operating System", 79); hm.put("Networking", 80); Map<String, Integer> hm1 = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : hm1.entrySet()) { System.out.println(en.getKey() + ": " + en.getValue()); } } }
Python # Python program to sort dictionary by values # function to sort dictionary by values def sortByValue(hm): # Create a list from elements of dictionary list_ = list(hm.items()) # Sort the list using lambda expression list_.sort(key=lambda i: i[1]) # put data from sorted list to dictionary temp = dict() for aa in list_: temp[aa[0]] = aa[1] return temp # Driver Code if __name__ == "__main__": hm = {} # enter data into dictionary hm["Math"] = 98 hm["Data Structure"] = 85 hm["Database"] = 91 hm["Java"] = 95 hm["Operating System"] = 79 hm["Networking"] = 80 hm1 = sortByValue(hm) # print the sorted dictionary for key, value in hm1.items(): print(f"{key}: {value}")
C# // C# program to sort dictionary by values using System; using System.Collections.Generic; using System.Linq; class GFG { // function to sort dictionary by values static Dictionary<string, int> sortByValue(Dictionary<string, int> hm) { // Create a list from elements of Dictionary List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>(hm); // Sort the list using lambda expression list.Sort((i1, i2) => i1.Value.CompareTo(i2.Value)); // put data from sorted list to dictionary Dictionary<string, int> temp = new Dictionary<string, int>(); foreach (var aa in list) { temp[aa.Key] = aa.Value; } return temp; } // Driver Code public static void Main() { Dictionary<string, int> hm = new Dictionary<string, int>(); // enter data into dictionary hm["Math"] = 98; hm["Data Structure"] = 85; hm["Database"] = 91; hm["Java"] = 95; hm["Operating System"] = 79; hm["Networking"] = 80; Dictionary<string, int> hm1 = sortByValue(hm); // print the sorted dictionary foreach (var en in hm1) { Console.WriteLine(en.Key + ": " + en.Value); } } }
JavaScript // JavaScript program to sort dictionary by values // function to sort dictionary by values function sortByValue(hm) { // Create a list from elements of dictionary let list = Object.entries(hm); // Sort the list using lambda expression list.sort((i1, i2) => i1[1] - i2[1]); // put data from sorted list to dictionary let temp = {}; for (let aa of list) { temp[aa[0]] = aa[1]; } return temp; } // Driver Code let hm = {}; // enter data into dictionary hm["Math"] = 98; hm["Data Structure"] = 85; hm["Database"] = 91; hm["Java"] = 95; hm["Operating System"] = 79; hm["Networking"] = 80; let hm1 = sortByValue(hm); // print the sorted dictionary for (let key in hm1) { console.log(key + ": " + hm1[key]); }
OutputOperating System: 79 Networking: 80 Data Structure: 85 Database: 91 Java: 95 Math: 98
Time Complexity: O(n * log(n)), required to traverse through the HashMap. Here n is the number of entries in the HashMap.
Space Complexity: O(n), required to store the key-value pairs in an auxiliary array.
Using Streams in Java
The idea is to use the stream() method to get the stream of entrySet followed by the lambda expression inside sorted() method to sort the stream and finally, we will convert it into a map using toMap() method. Inside the toMap() method, we use the LinkedHashMap::new method reference to retain the sorted order of the map.
Java // Java program to sort hashmap by values import java.lang.*; import java.util.*; import java.util.stream.Collectors; class GFG { // function to sort hashmap by values static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { HashMap<String, Integer> temp = hm.entrySet().stream().sorted((i1, i2)-> i1.getValue().compareTo(i2.getValue())).collect( Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); return temp; } public static void main(String[] args) { HashMap<String, Integer> hm = new HashMap<String, Integer>(); // enter data into hashmap hm.put("Math", 98); hm.put("Data Structure", 85); hm.put("Database", 91); hm.put("Java", 95); hm.put("Operating System", 79); hm.put("Networking", 80); Map<String, Integer> hm1 = sortByValue(hm); // print the sorted hashmap for (Map.Entry<String, Integer> en : hm1.entrySet()) { System.out.println(en.getKey() + ": " + en.getValue()); } } }
OutputOperating System: 79 Networking: 80 Data Structure: 85 Database: 91 Java: 95 Math: 98
Similar Reads
Sorting a HashMap according to keys in Java
We are given the details of marks scored by students in form of a HashMap, where the name of the student is the Key and the marks scored is the Value. Our task is to sort the map according to the key values i.e the names of the students in the alphabetical(lexicographical) order.Examples: Input : Ke
6 min read
Sorting using trivial hash function
We have read about various sorting algorithms such as heap sort, bubble sort, merge sort and others. Here we will see how can we sort N elements using a hash array. But this algorithm has a limitation. We can sort only those N elements, where the value of elements is not large (typically not above 1
15+ min read
HashMap values() Method in Java
The java.util.HashMap.values() method of HashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap. Syntax: Hash_Map.values() Parameters: The method does not accept any parameters. Return Value: The method i
2 min read
IdentityHashMap values() Method in Java
The java.util.IdentityHashMap.values() method of IdentityHashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the Map. Syntax: Identity_Hash_Map.values() Parameters: The method does not accept any parameters. Retur
2 min read
ConcurrentHashMap values() method in Java with Examples
The values() method of ConcurrentHashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the ConcurrentHashMap. Syntax: ConcurrentHashMap.values() Parameters: The method does not accept any parameters. Return Value: T
2 min read
ConcurrentHashMap in Java
In Java, the ConcurrentHashMap is a thread-safe implementation of the Map interface. It allows multiple threads to read and write data simultaneously, without the need for locking the entire map. Unlike a regular HashMap, which is not thread-safe, ConcurrentHashMap ensures that the operations are th
15+ min read
HashMap and TreeMap in Java
HashMap and TreeMap are part of collection framework. HashMapjava.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value pair<Key, Value>. HashMap<K, V> hmap = new HashMap<K, V>(); Let us consider below example where we have to count occurrences
5 min read
ConcurrentHashMap putAll() method in Java
The putAll() method in Java's ConcurrentHashMap class is used to copy all the key-value mappings from a specified map to the current map. It has the following signature: void putAll(Map<? extends K,? extends V> m) where: m is the map whose key-value mappings are to be copied to the current map
3 min read
IdentityHashMap hashCode() Method in Java
The java.util.IdentityHashMap.hashCode() method in Java is used to fetch the hash code value of a particular this IdentityHashMap. A map consists of a number of buckets to store the key-value pair. Each bucket has a unique identity and when a key-value pair is inserted into a bucket, the key's hashc
2 min read
How to check if a key exists in a HashMap in Java
Given a HashMap and a key in Java, the task is to check if this key exists in the HashMap or not. Examples: Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2 Output: true Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 10 Output: false Using Iterator (Not Efficient): Get the HashMap a
4 min read