Sort hashmap by value

Hashmap is key-value pair data structure. Most time you sort the hashmap by the key. But sometimes you need to sort the hashmap by value, and the value is custom defined objects. The easy way is to use the built-in APIs provided by languages. Java, JavaScript and Python all provides the APIs. The syntax can be confusing. You can use the examples here as template for your project.

sort hashmap by value

How to sort hashmap by value is Java?

In Java, you can use method Entry.comparingByValue(). You save all values of the hashmap to a list, by using entrySet(). Then call sort method with predefined built-in method Entry.comparingByValue(). It calls the object’s compareTo() method defined in the class for sorting.

How to sort hashmap by value in JavaScript?

In JavaScript, you use lambda expression =>
newMap = new Map([…mapObj.entries()].sort(([k1,v1], [k2,v2])=> { return v1.attrName – v2.attrName; }));
k and v represents key and value respectively.

How to sort hashmap by value in Python?

In Python, you uses lambda expression lambda x:
newMap = sorted(mapObj.items(), key = lambda x: (x[1].attrName))
x[0] represents key,  x[1] represents value

Java

JavaScript

Python

Output:
Black Pearl – Mango 15.7 Philippines
Mayflower – Banana 20.13 Hawaii
Victory – Orange 30.7 Florida
Queen Mary – Apple 40.09 Japan

O Notation:
Time complexity: O(nlogn), n is the number of elements in hash.
Space complexity: O(n)


HashMap sort by key

Comments are closed