Is there any correct way to get top N elements from SortedMap? My variant is:
val sortedMap = map.filterValues { it in sortedValues }.toSortedMap()
if (sortedMap.size <= 20) {
return sortedMap
}
var result = mutableMapOf<String, Int>()
for ((key, value) in sortedMap) {
result[key] = value
if (result.size == 20) {
break
}
}
val first20AsList: List<Map.Entry<String, Int>> = sortedMap.asIterable().take(20)
val first20AsMap: Map<String, Int> = first20AsList.associate { it.toPair() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With