toSortedMap

fun <K : Comparable<K>, V> Map<out K, V>.toSortedMap(): SortedMap<K, V> (source)

Platform and version requirements: JVM

Converts this Map to a SortedMap so iteration order will be in key order.

import kotlin.test.*
import java.util.*

fun main(args: Array<String>) {
//sampleStart
val map = mapOf(Pair("c", 3), Pair("b", 2), Pair("d", 1))
val sorted = map.toSortedMap()
println(sorted.keys) // [b, c, d]
println(sorted.values) // [2, 3, 1]
//sampleEnd
}
fun <K, V> Map<out K, V>.toSortedMap(
    comparator: Comparator<in K>
): SortedMap<K, V>
(source)

Platform and version requirements: JVM

Converts this Map to a SortedMap using the given comparator so that iteration order will be in the order defined by the comparator.

import kotlin.test.*
import java.util.*

fun main(args: Array<String>) {
//sampleStart
val map = mapOf(Pair("abc", 1), Pair("c", 3), Pair("bd", 4), Pair("bc", 2))
val sorted = map.toSortedMap(compareBy<String> { it.length }.thenBy { it })
println(sorted.keys) // [c, bc, bd, abc]
//sampleEnd
}