Created
July 8, 2020 22:06
-
-
Save telendt/df63b67c0e3784567b9283c4f8e0dd7a to your computer and use it in GitHub Desktop.
generic top-k collector in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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