HashMap object as key and sort by key

HashMap object as key introduces how to use object as key and how to sort by key when the key is an object. In HashMap, the key can be any data type. The most common used data types are String and Integer. When you use custom defined object as key, you have to specify how to order them. Since the syntax can be confusing, you can use the example here as template.

How to sort by key in hash map?

  1. Java uses TreeMap

    you define the class that implements Comparable and write compareTo method to define the order. Then declare the Map as TreeMap. When adding data to a TreeMap, it automatically sort by key for you.

  2. JavaScript uses Lambda expression =>

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

  3. Python uses lambda expression lambda x:

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




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

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

HashMap sort by value
Object as key and sort in HashMap(YouTube)

Comments are closed