0
0
KotlinHow-ToBeginner · 3 min read

How to Sort Map by Value in Kotlin: Simple Guide

In Kotlin, you can sort a map by its values using toList() to convert it to a list of pairs, then sortedBy { it.second } to sort by the value. Finally, convert it back to a map with toMap() if needed.
📐

Syntax

To sort a map by its values in Kotlin, use the following pattern:

  • map.toList(): Converts the map to a list of key-value pairs.
  • sortedBy { it.second }: Sorts the list by the value part of each pair.
  • toMap(): Converts the sorted list back to a map.
kotlin
val sortedMap = map.toList().sortedBy { it.second }.toMap()
💻

Example

This example shows how to sort a map of names and scores by the scores in ascending order.

kotlin
fun main() {
    val scores = mapOf("Alice" to 50, "Bob" to 75, "Charlie" to 60)
    val sortedScores = scores.toList().sortedBy { it.second }.toMap()
    println(sortedScores)
}
Output
{Alice=50, Charlie=60, Bob=75}
⚠️

Common Pitfalls

One common mistake is trying to sort the map directly without converting it to a list first, which is not supported because maps are unordered collections. Another pitfall is expecting the original map to be changed; sorting creates a new map or list.

kotlin
fun main() {
    val map = mapOf("a" to 3, "b" to 1, "c" to 2)
    // Wrong: map.sortedBy { it.value } // This returns a list, not a map

    // Right way:
    val sortedMap = map.toList().sortedBy { it.second }.toMap()
    println(sortedMap)
}
Output
{b=1, c=2, a=3}
📊

Quick Reference

Remember these key functions for sorting maps by value in Kotlin:

FunctionPurpose
toList()Convert map to list of pairs
sortedBy { it.second }Sort list by value
toMap()Convert sorted list back to map

Key Takeaways

Convert the map to a list before sorting by values using toList().
Use sortedBy { it.second } to sort by the map's values.
Convert the sorted list back to a map with toMap() if you need a map result.
Sorting creates a new collection; the original map stays unchanged.
Maps are unordered, so sorting returns a LinkedHashMap preserving order.