Sort hashmap by key

Hashmap is key-value pair data structure. The key can be any data type. The most common used data types are string and integer. Sometime, custom defined object can be a key as well. Then you have to specify how to order them. This post introduces how to sort hashmap by key. In Java, you use TreeMap. In JavaScript and Python, you use lambda expressions.

sort hashmap by key

How to sort hashmap by key in Java?

In Java, you use 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.

How to sort hashmap by key in JavaScript?

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

How to sort hashmap by key in Python?

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

Java

JavaScript

Python

Output:
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

Comments are closed