How to sort LinkedHashMap by values in Kotlin?

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) -> /* ... */ }

I don't why you have accepted the complicated answer.

var mapImmutable = mapOf<Int, Int>(1 to 11, 2 to 22, 3 to 33)

println(mapImmutable.toSortedMap(compareByDescending { mapImmutable[it] })) //{3=33, 2=22, 1=11}

mapImmutable[it] is the value
just pass it to compareBy function

Tags:

Sorting

Kotlin