PriorityQueue队列

PriorityQueue队列
叶小楠PriorityQueue队列
数据结构:
PriorityQueue
PriorityQueue
是 Java 提供的一个基于堆实现的优先队列。- 它的特点是每次从队列中取出的元素总是优先级最高的元素。
类型参数:
Map.Entry<String, Integer>
- 这个优先队列存储的元素类型是
Map.Entry<String, Integer>
。 Map.Entry<String, Integer>
通常用于表示键值对,比如从一个Map
(如HashMap
或TreeMap
)中获取的条目。
- 这个优先队列存储的元素类型是
构造器参数:
Comparator
- 优先队列默认是最小堆(按自然顺序从小到大排列),但可以通过传递一个自定义的比较器(
Comparator
)来指定排序规则。 (a, b) -> b.getValue() - a.getValue()
是一个 lambda 表达式,用于定义自定义比较器。
- 优先队列默认是最小堆(按自然顺序从小到大排列),但可以通过传递一个自定义的比较器(
比较逻辑:
(a, b) -> b.getValue() - a.getValue()
这里的
a
和b
是两个Map.Entry<String, Integer>
类型的元素。b.getValue() - a.getValue()
Entry1
2
3
表示按Integer1
2
3
的值(1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
部分)从大到小排序:
- 如果 `b.getValue()` > `a.getValue()`,返回正值,`b` 会排在 `a` 的前面。
- 如果 `b.getValue()` < `a.getValue()`,返回负值,`a` 会排在 `b` 的前面。
- 如果相等,返回 0,顺序不变。
5. **最终效果**
- 该优先队列会将键值对按照 `Integer` 值从大到小排序。
- 每次调用 `poll()` 方法,都会取出值最大的键值对。
### 示例代码
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
PriorityQueue<Map.Entry<String, Integer>> Data = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
// 模拟 Map.Entry 数据
Map.Entry<String, Integer> entry1 = Map.entry("Alice", 10);
Map.Entry<String, Integer> entry2 = Map.entry("Bob", 20);
Map.Entry<String, Integer> entry3 = Map.entry("Charlie", 15);
// 添加到优先队列
Data.offer(entry1);
Data.offer(entry2);
Data.offer(entry3);
// 输出按照值从大到小的顺序
while (!Data.isEmpty()) {
Map.Entry<String, Integer> entry = Data.poll();
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
输出
1 | Bob: 20 |