Top-K With A Bounded Min Heap
Poll new entries into a bounded min-heap of size k: overflow evicts the smallest survivor, and a final sort turns the heap into a ranked list.
Code
import java.util.List;
import java.util.PriorityQueue;
public class TopKSpenders {
// 有界 min-heap:堆顶始终是当前前 k 名里最小的,超员先弹它
static List<String> topK(List<String> names, long[] amounts, int k) {
PriorityQueue<long[]> heap = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
for (int i = 0; i < names.size(); i++) {
heap.offer(new long[] {amounts[i], i});
if (heap.size() > k) {
heap.poll();
}
}
return heap.stream()
.sorted((a, b) -> Long.compare(b[0], a[0]))
.map(e -> names.get((int) e[1]) + "=" + e[0])
.toList();
}
public static void main(String[] args) {
List<String> names = List.of("ada", "bob", "cyd", "dee", "eli");
long[] amounts = {42, 97, 13, 88, 60};
System.out.println(topK(names, amounts, 3)); // [bob=97, dee=88, eli=60]
}
}How the snippet gets there
All of the logic lives in the class TopKSpenders and the functions topK and main.
A single loop drives the file — for (int i = 0; i < names.size(); i++). The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
What to watch for
- The construction leaves no dependency behind: no registry, no lockfile entry.
Using it
The entry-point signature is static List<String> topK(List<String> names, long[] amounts, int k)
There are 1 call inside main — topK — executed top to bottom.
Key statements
return heap.stream()
.sorted((a, b) -> Long.compare(b[0], a[0]))
.map(e -> names.get((int) e[1]) + "=" + e[0])
.toList();
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Top-K With A Bounded Min Heap?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.