Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get top N elements in SortedMap?

Tags:

kotlin

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
    }
}
like image 312
Galina Avatar asked Jun 16 '26 20:06

Galina


1 Answers

val first20AsList: List<Map.Entry<String, Int>> = sortedMap.asIterable().take(20)
val first20AsMap: Map<String, Int> = first20AsList.associate { it.toPair() }
like image 171
Михаил Нафталь Avatar answered Jun 19 '26 11:06

Михаил Нафталь



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!