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?
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?
1 Answer
Reset to default 1There 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.
toSortedMap()
is missing, the problem is that the result typeSortedMap
doesn't exist. Please edit the question to provide a minimal reproducible example and clearly specify what the resulting type shoul be. – tyg Commented Feb 14 at 16:05