Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort LinkedHashMap by values in Kotlin?

Tags:

To sort by keys I can use

map.toSortedMap() 

But what is the best way to sort LinkedHashMap by values in Kotlin?

like image 924
diesersamat Avatar asked Jul 28 '17 14:07

diesersamat


People also ask

How do you sort a map by key-value?

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.


2 Answers

map.toList()     .sortedBy { (key, value) -> value }     .toMap() 
like image 85
Alex Filatov Avatar answered Sep 21 '22 21:09

Alex Filatov


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) -> /* ... */ } 
like image 38
Willi Mentzel Avatar answered Sep 18 '22 21:09

Willi Mentzel