懂了:你要的是 堆(Heap)数据结构,在 Java 里基本就是用 PriorityQueue 来实现;最小堆是默认行为,自定义比较用 Comparator

1) 最小堆(默认)

PriorityQueue<Integer> pq = new PriorityQueue<>(); // 默认最小堆
pq.add(5);
pq.add(2);
pq.add(7);
System.out.println(pq.poll()); // 2

2) 最小堆 + 自定义比较(对象)

比如按 score 小的优先;如果分数相同按 id 小的优先:

import java.util.*;

class Node {
    int id;
    int score;
    Node(int id, int score) { this.id = id; this.score = score; }
}

public class Main {
    public static void main(String[] args) {
        PriorityQueue<Node> pq = new PriorityQueue<>(
            (a, b) -> {
                if (a.score != b.score) return Integer.compare(a.score, b.score); // score小优先
                return Integer.compare(a.id, b.id); //풀  tie-breaker
            }
        );

        pq.add(new Node(2, 10));
        pq.add(new Node(1, 10));
        pq.add(new Node(3, 5));

        while (!pq.isEmpty()) {
            Node x = pq.poll();
            System.out.println(x.id + " " + x.score);
        }
        // 输出:
        // 3 5
        // 1 10
        // 2 10
    }
}

3) 常见坑:比较器别写

a - b

因为可能溢出,正确做法是 Integer.compare(a, b) / Long.compare(a, b)。

✅ 正确:

(a, b) -> Integer.compare(a.score, b.score)

❌ 不推荐:

(a, b) -> a.score - b.score

4) 最小堆 vs 最大堆

最大堆整数例子:

PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());

如果你说下你的具体需求(比如“按距离最小、距离相同按时间最早”或“多字段排序、需要稳定性”等),我可以给你一份更贴合的 Comparator 模板(含 long/浮点/空值处理)。