Kotlin Tutorials

Kotlin Map toSortedMap()
Syntax & Examples

Syntax of toSortedMap()

There are 2 variations for the syntax of Map.toSortedMap() extension function. They are:

1.
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.

2.
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.



✐ Examples

1 Convert to sorted map

In this example,

  • We create a map named map1 containing integer keys and character values.
  • We then apply the toSortedMap() function on map1.
  • As a result, a new sorted map containing all key-value pairs from map1 sorted by keys in natural order is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf(3 to 'c', 1 to 'a', 2 to 'b')
    val result = map1.toSortedMap()
    println(result)
}

Output

{1=a, 2=b, 3=c}

2 Convert to sorted map

In this example,

  • We create a map named map2 containing character keys and integer values.
  • We then apply the toSortedMap() function on map2.
  • As a result, a new sorted map containing all key-value pairs from map2 sorted by keys in natural order is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = mapOf('c' to 3, 'a' to 1, 'b' to 2)
    val result = map2.toSortedMap()
    println(result)
}

Output

{a=1, b=2, c=3}

3 Convert to sorted map

In this example,

  • We create a map named map3 containing string keys and integer values.
  • We then apply the toSortedMap() function on map3.
  • As a result, a new sorted map containing all key-value pairs from map3 sorted by keys in natural order is returned.
  • We print the result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3 = mapOf("cherry" to 3, "apple" to 1, "banana" to 2)
    val result = map3.toSortedMap()
    println(result)
}

Output

{apple=1, banana=2, cherry=3}

Summary

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.