There are 2 variations for the syntax of Map.toSortedMap() extension function. They are:
fun <K : Comparable<K>, V> Map<out K, V>.toSortedMap(): SortedMap<K, V>
This extension function converts this Map to a SortedMap. The resulting SortedMap determines the equality and order of keys according to their natural sorting order.
fun <K, V> Map<out K, V>.toSortedMap( comparator: Comparator<in K> ): SortedMap<K, V>
This extension function converts this Map to a SortedMap. The resulting SortedMap determines the equality and order of keys according to the sorting order provided by the given comparator.
In this example,
map1
containing integer keys and character values.toSortedMap()
function on map1
.map1
sorted by keys in natural order is returned.fun main(args: Array<String>) {
val map1 = mapOf(3 to 'c', 1 to 'a', 2 to 'b')
val result = map1.toSortedMap()
println(result)
}
{1=a, 2=b, 3=c}
In this example,
map2
containing character keys and integer values.toSortedMap()
function on map2
.map2
sorted by keys in natural order is returned.fun main(args: Array<String>) {
val map2 = mapOf('c' to 3, 'a' to 1, 'b' to 2)
val result = map2.toSortedMap()
println(result)
}
{a=1, b=2, c=3}
In this example,
map3
containing string keys and integer values.toSortedMap()
function on map3
.map3
sorted by keys in natural order is returned.fun main(args: Array<String>) {
val map3 = mapOf("cherry" to 3, "apple" to 1, "banana" to 2)
val result = map3.toSortedMap()
println(result)
}
{apple=1, banana=2, cherry=3}
In this Kotlin tutorial, we learned about toSortedMap() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.