kotlinkotlin-multiplatform

KMP Map sorting


Because JVM TreeMap implementation is not available in KMP common code, the toSortedMap() extension function is also unavailable. So, what are the alternatives to sort the map by key values?


Solution

  • There is no such thing as a sorted map in Kotlin. Nor is there really a need for it.

    If you just want a sorted list of all keys you can use this:

    myMap.keys.sorted()
    

    If you want a list of all values, sorted by their keys, use this:

    myMap.entries.sortedBy { it.key }.map { it.value }
    

    If you just want to iterate all key/value pairs in key order, then you can do this:

    myMap.entries.sortedBy { it.key }
        .forEach { (key, value) ->
            println("$key -> $value")
        }
    

    All of the above has in common that you do not sort the map itself, you only sort the keys, values or both (i.e., the entries). The result will always be a List, not a Map, though.