Sort a Map By Values in Kotlin
The easy way to sort Kotlin Map by value is by doing below steps:- Convert Map to array using toList() function.
- Sort converted array using
sortedBy
. - convert sorted array to Map using
toMap()
.
See below example
fun main(args: Array<String>) {
var capitals = hashMapOf<String, String>()
capitals.put("User 1", "James Bond")
capitals.put("User 2", "William Smith")
capitals.put("User 3", "Joshua Spencer")
capitals.put("User4", "Robert Williams")
val result = capitals.toList().sortedBy { (_, value) -> value}.toMap()
for (entry in result) {
print("Key: " + entry.key)
println(" Value: " + entry.value)
}
}
Output
Key: User 1 Value: James Bond
Key: User 3 Value: Joshua Spencer
Key: User4 Value: Robert Williams
Key: User 2 Value: William Smith
Key: User 3 Value: Joshua Spencer
Key: User4 Value: Robert Williams
Key: User 2 Value: William Smith