toSortedMap

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

Converts this Map to a SortedMap. The resulting SortedMap determines the equality and order of keys according to their natural sorting order.

Note that if the natural sorting order of keys considers any two keys of this map equal (this could happen if the equality of keys according to Comparable.compareTo is inconsistent with the equality according to Any.equals), only the value associated with the last of them gets into the resulting map.

Since Kotlin

1.0

Samples

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

fun main() { 
   //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)

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.

Note that if the comparator considers any two keys of this map equal, only the value associated with the last of them gets into the resulting map.

Since Kotlin

1.0

Samples

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

fun main() { 
   //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
}