最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

kotlin - KMP Map sorting - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question asked Feb 14 at 15:14 xephosbotxephosbot 3055 silver badges18 bronze badges 1
  • The problem is not that toSortedMap() is missing, the problem is that the result type SortedMap 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
Add a comment  | 

1 Answer 1

Reset to default 1

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.

发布评论

评论列表(0)

  1. 暂无评论