To sort a map by keys in Kotlin, you can use the `toSortedMap` method, which returns a new map with the keys sorted. This method provides a straightforward way to ensure the map is sorted by keys.
We can sort a map by keys in Kotlin by using the `toSortedMap` method, which returns a new map with the keys sorted.
For example,
unsortedMap
with some key-value pairs. In this example, the map has integer keys and string values.toSortedMap
method to create a new map named sortedMap
that contains the same key-value pairs but with sorted keys.println
function to verify the sorting.fun main() {
// Declare and initialize an unsorted map
val unsortedMap = mapOf(3 to "three", 1 to "one", 2 to "two")
// Sort the map by keys
val sortedMap = unsortedMap.toSortedMap()
// Print the sorted map
println("Sorted Map by Keys: $sortedMap")
}
Sorted Map by Keys: {1=one, 2=two, 3=three}
We can sort a map by keys in descending order in Kotlin by using the `toSortedMap` method with a custom comparator.
For example,
unsortedMap
with some key-value pairs. In this example, the map has integer keys and string values.toSortedMap
method with a custom comparator to create a new map named sortedMap
that contains the same key-value pairs but with keys sorted in descending order.println
function to verify the sorting.fun main() {
// Declare and initialize an unsorted map
val unsortedMap = mapOf(3 to "three", 1 to "one", 2 to "two")
// Sort the map by keys in descending order
val sortedMap = unsortedMap.toSortedMap(compareByDescending { it })
// Print the sorted map
println("Sorted Map by Keys (Descending): $sortedMap")
}
Sorted Map by Keys (Descending): {3=three, 2=two, 1=one}
We can sort a map with string keys in Kotlin by using the `toSortedMap` method, which returns a new map with the keys sorted alphabetically.
For example,
unsortedMap
with some key-value pairs. In this example, the map has string keys and integer values.toSortedMap
method to create a new map named sortedMap
that contains the same key-value pairs but with keys sorted alphabetically.println
function to verify the sorting.fun main() {
// Declare and initialize an unsorted map
val unsortedMap = mapOf("three" to 3, "one" to 1, "two" to 2)
// Sort the map by keys
val sortedMap = unsortedMap.toSortedMap()
// Print the sorted map
println("Sorted Map by Keys: $sortedMap")
}
Sorted Map by Keys: {one=1, three=3, two=2}
In this tutorial, we learned How to Sort a Map by Keys in Kotlin language with well detailed examples.