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.
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.
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.
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
public class HashMapSortByValue { static class Fruit implements Comparable<Fruit>{ String name; double price; String origin; public Fruit(String itm, double pr, String loc){ this.name = itm; this.price = pr; this.origin = loc; } public int compareTo(Fruit y) { return (int) this.price - (int) y.price; } public String toString() { return name + " " + price + " " + origin; } } //Sort by value, Time O(nlogn), Space O(n), n is number of fruits in map public static Map<String, Fruit> sortByValue(Map<String, Fruit> map) { List<Map.Entry<String, Fruit>> list = new ArrayList<>(map.entrySet()); list.sort(Map.Entry.comparingByValue()); Map<String, Fruit> sorted = new LinkedHashMap<>(); for (Map.Entry<String, Fruit> entry: list) { sorted.put(entry.getKey(), entry.getValue()); } return sorted; } public static void main(String a[]) { Fruit fruit1 = new Fruit("Banana", 20.13, "Hawaii"); Fruit fruit2 = new Fruit("Apple", 40.09, "Japan"); Fruit fruit3 = new Fruit("Orange", 30.7, "Florida"); Fruit fruit4 = new Fruit("Mango", 15.7, "Philippines"); //object as value Map<String, Fruit> fruitsAsValue = new HashMap<>(); fruitsAsValue.put("Mayflower", fruit1); fruitsAsValue.put("Queen Mary", fruit2); fruitsAsValue.put("Victory", fruit3); fruitsAsValue.put("Black Pearl", fruit4); //call method Map<String, Fruit> res2= sortByValue(fruitsAsValue); for (String h: res2.keySet() ) System.out.println(h + " - " + res2.get(h)); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
class Fruit { constructor(itm, pr, loc){ this.name = itm; this.price = pr; this.origin = loc; } toString() { return this.name + " " + this.price + " " + this.origin; } } const fruit1 = new Fruit("Banana", 20.13, "Hawaii"); const fruit2 = new Fruit("Apple", 40.09, "Japan"); const fruit3 = new Fruit("Orange", 30.7, "Florida"); const fruit4 =new Fruit("Mango", 15.7, "Philippines"); //object as value const fruitAsValue = new Map(); fruitAsValue.set("Mayflower", fruit1); fruitAsValue.set("Queen Mary", fruit2); fruitAsValue.set("Victory", fruit3); fruitAsValue.set("Black Pearl", fruit4); //sort by value, Time O(nlogn), Space O(n), n is number of fruits in map var res2 = new Map([...fruitAsValue.entries()].sort(([k1,v1], [k2,v2])=> { return v1.price - v2.price; })); console.log(res2); |
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Fruit : def __init__(self, itm, pr, loc): self.name = itm self.price = pr self.origin = loc def __str__(self): return self.name + " " + str(self.price) + " " + self.origin fruit1 = Fruit("Banana", 20.13, "Hawaii") fruit2 = Fruit("Apple", 40.09, "Japan") fruit3 = Fruit("Orange", 30.7, "Florida") fruit4 = Fruit("Mango", 15.7, "Philippines") #object as value fruitAsValue ={} fruitAsValue["Mayflower"] = fruit1 fruitAsValue["Queen Mary"] = fruit2 fruitAsValue["Victory"] = fruit3 fruitAsValue["Black Pearl"] = fruit4 #sort by value, Time O(nlogn), Space O(n), n is number of fruits in map res2 = sorted(fruitAsValue.items(), key = lambda x: x[1].price) for k, v in res2: print(k + " - " + str(v)) print() |
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)