W3cubDocs

/Kotlin

toSortedMap

Platform and version requirements: JVM (1.0)
fun <K : Comparable<K>, V> Map<out K, V>.toSortedMap(): SortedMap<K, V>

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.

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
}
Platform and version requirements: JVM (1.0)
fun <K, V> Map<out K, V>.toSortedMap(
    comparator: Comparator<in K>
): SortedMap<K, V>

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.

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
}

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-sorted-map.html