Skip to content

Instantly share code, notes, and snippets.

@telendt
Created July 8, 2020 22:06
Show Gist options
  • Save telendt/df63b67c0e3784567b9283c4f8e0dd7a to your computer and use it in GitHub Desktop.
Save telendt/df63b67c0e3784567b9283c4f8e0dd7a to your computer and use it in GitHub Desktop.
generic top-k collector in Kotlin
import java.util.PriorityQueue
import java.util.stream.Collector
import java.util.stream.Collector.Characteristics
fun <T : Comparable<T>> topN(n: Int) = Collector.of(
{ PriorityQueue<T>(n + 1) },
{ queue, value: T ->
queue.add(value)
if (queue.size > n) {
queue.poll()
}
},
{ first, second ->
for (value in second) {
first.add(value)
if (first.size > n) {
first.poll()
}
}
first
},
{ queue -> queue.sortedDescending() },
arrayOf(Characteristics.UNORDERED)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment