Solution
In my opinion the best way is to use asSequence()
because it is evaluated lazily:
return sortedMap.asSequence().take(20).map{ it.toPair() }.toMap()
Information on Lazy evaluation
In general it is often favorable to use lazy variants of iterable containers, because it means that in many cases not the whole datastructure needs to be evaluated but just the portion of data that is required.
In your case that would be the first N in the SortedMap
. If it really happens to result in a performance advantage is questionable, but at least it is possible.
Some Information from stack-overflow and kotlin on lazy sequences:
Old Answer:
This answer was improved in some details thanks to the comment by @IR42. Before I used the spread
operator for conversion to a sorted-map again (via sortedMapOf
), and map { it.key to it.value }
instead of { it.toPair() }
:
return sortedMapOf(
*sortedMap.asSequence().take(20)
.map{ it.key to it.value }
.toList().toTypedArray())