调用toSortedMap后Kotlin Map的List值元素数量异常减少问题
toSortedMap reduce the size of value lists? First off, this is not a bug in TreeMap or the Kotlin library—the toSortedMap method only handles sorting keys and never modifies the value collections themselves. The issue you're seeing is almost certainly related to how your comparator handles key equality in the TreeMap.
Let's break down the root cause:
TreeMap uses the comparator you provide to determine key equality. If your comparator returns 0 for two different keys, TreeMap treats those keys as identical. This means the later entry will overwrite the earlier one in the map, which makes it look like your value lists have fewer elements (when in reality, entire key-value pairs are being merged/overwritten).
Looking at your comparator:
compareBy { categoriesKeysOrdersMap[it] }
If two distinct keys from categoriesKeys map to the same integer value in categoriesKeysOrdersMap, your comparator will return 0 for them. TreeMap will then merge those entries, keeping only the last one processed. That's why you're losing entries (and seeing smaller value lists) after calling toSortedMap.
How to fix this:
You need to ensure your comparator can distinguish between all unique keys. The easiest way is to add a secondary comparison based on the key itself, so even if two keys have the same order value, they're still treated as distinct:
.toSortedMap(compareBy({ categoriesKeysOrdersMap[it] }, { it }))
This way, first we sort by the order value from categoriesKeysOrdersMap, and if two keys have the same order value, we fall back to sorting by the key's natural String order. TreeMap will no longer merge these keys, and all your original value lists will remain intact.
Quick verification step:
Before and after calling toSortedMap, print out the size of the map and the keys present. You'll likely see that some keys are missing after sorting—this confirms the key merging issue caused by the comparator returning 0 for distinct keys.
内容的提问来源于stack exchange,提问作者Olexii Muraviov

