How to Sort Map by Key in Kotlin: Simple Guide
In Kotlin, you can sort a map by its keys using the
toSortedMap() function, which returns a new map sorted by keys. Alternatively, you can use entries.sortedBy { it.key } to get a sorted list of pairs by key.Syntax
The main way to sort a map by key in Kotlin is using toSortedMap(). This function returns a new SortedMap with keys in ascending order.
Another way is to use entries.sortedBy { it.key } which returns a list of map entries sorted by key.
kotlin
val sortedMap = originalMap.toSortedMap()
val sortedList = originalMap.entries.sortedBy { it.key }Example
This example shows how to sort a map by its keys using toSortedMap(). It prints the original map and the sorted map.
kotlin
fun main() {
val originalMap = mapOf(3 to "Three", 1 to "One", 2 to "Two")
println("Original map: $originalMap")
val sortedMap = originalMap.toSortedMap()
println("Sorted map by key: $sortedMap")
}Output
Original map: {3=Three, 1=One, 2=Two}
Sorted map by key: {1=One, 2=Two, 3=Three}
Common Pitfalls
A common mistake is trying to sort the map in place, but Kotlin maps are immutable by default, so sorting returns a new map.
Also, using sortedBy on a map directly returns a list, not a map, which may confuse beginners.
kotlin
fun main() {
val map = mapOf(2 to "B", 1 to "A")
// Wrong: This does not sort the map in place
// map.sortedBy { it.key } // returns List, not Map
// Right: Use toSortedMap() to get a sorted map
val sortedMap = map.toSortedMap()
println(sortedMap)
}Output
{1=A, 2=B}
Quick Reference
- toSortedMap(): Returns a new map sorted by keys.
- entries.sortedBy { it.key }: Returns a list of entries sorted by key.
- Maps are immutable by default; sorting returns a new collection.
Key Takeaways
Use toSortedMap() to get a new map sorted by keys in ascending order.
sortedBy on map entries returns a list, not a map.
Kotlin maps are immutable; sorting creates a new collection.
toSortedMap() is the simplest way to sort a map by key.
Remember to print or use the returned sorted map, as original map stays unchanged.