Open In App

Sorting a Hashmap according to values

Last Updated : 03 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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]);
}

Output
Operating 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]);
}

Output
Operating 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());
        }
    }
}

Output
Operating System: 79
Networking: 80
Data Structure: 85
Database: 91
Java: 95
Math: 98

Next Article
Article Tags :
Practice Tags :

Similar Reads