To sort by keys I can use
map.toSortedMap()
But what is the best way to sort LinkedHashMap by values in Kotlin?
Step 1: Create a TreeMap in java with a custom comparator. Step 2: Comparator should compare based on values and then based on the keys. Step 3: Put all key-value pairs from the hashmap into the treemap. Step 4: return the treemap.
map.toList() .sortedBy { (key, value) -> value } .toMap()
You can use sortedBy
with destructuring syntax and leave the first argument blank:
map.toList().sortedBy { (_, value) -> value }.toMap()
or you can do it without destructuring syntax (as mentioned by aksh1618 in the comments):
map.toList().sortedBy { it.second }.toMap()
and if you want to iterate the result right away, you don't even need toMap()
:
map.toList() .sortedBy { it.second } .forEach { (key, value) -> /* ... */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With