HashMap sort 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.

How to sort by value in hash map?

  1. Java uses 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.

  2. JavaScript uses lambda expression =>

    use the following lambda syntax to sort map by value. k and v represents key and value respectively.
    newMap = new Map([…mapObj.entries()].sort(([k1,v1], [k2,v2])=> { return v1.attrName – v2.attrName; }));

  3. Python uses lambda expression lambda x:

    use the following lambda syntax to sort map by value. x[0] represents key,  x[1] represents value
    newMap = sorted(mapObj.items(), key = lambda x: (x[1].attrName))




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
Sort with lambda comparator
Object as key and sort in HashMap(YouTube)

Comments are closed