How can i sort HashMap<String,Int> order by their values in Kotlin?
Asked Answered
C

1

5

Here is my example, how can i do that in Kotlin?

var hashMapForTry = HashMap<String,Int>()

hashMapForTry.put("Hi",5)
hashMapForTry.put("What",7)
hashMapForTry.put("How",2)
hashMapForTry.put("Go",1)
hashMapForTry.put("Ford",9)
Cosmonautics answered 29/11, 2019 at 0:17 Comment(0)
C
14

You cannot sort a HashMap because it doesn't guarantee that its entries will be iterated in any particular order. You can, however, arrange the items into a LinkedHashMap which keeps the insertion order:

    val resultMap = hashMapForTry.entries.sortedBy { it.value }.associate { it.toPair() }

    println(resultMap)

Here the entries of hashMapForTry are sorted by entry value, then associate function converts the list of entries into a map that preserves the order of entries from that list.

The result type of this function is Map<String, Int>. If you need to mutate the result further, you can use associateTo function and specify an empty destination LinkedHashMap as a parameter:

....associateTo(LinkedHashMap()) { ... }
Claqueur answered 29/11, 2019 at 1:7 Comment(2)
Or a TreeMap which uses a comparator to determine the orderPunk
@AjahnCharles TreeMap uses a comparator to compare keys, it cannot be used to order them based on the corresponding values.Claqueur

© 2022 - 2024 — McMap. All rights reserved.