实现说明
真正干活的是类 TopKSpenders和函数 topK、main,其余都是接线。
文件的主干是一个循环——for (int i = 0; i < names.size(); i++)。转换以 stream 管道组织——数据源、中间操作、终端收集器各自独立可读。
使用要点
- 执行文件,
main会按顺序走完topK。
常见问题
「有界小顶堆选前 K 名」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
主要签名是 static List<String> topK(List<String> names, long[] amounts, int k)
核心语句
return heap.stream()
.sorted((a, b) -> Long.compare(b[0], a[0]))
.map(e -> names.get((int) e[1]) + "=" + e[0])
.toList();
代码示例
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]
}
}