看不懂Priority Queue流程
Can't understand Priority Queue process
String S = "aaaaaaaacabbbb";
if (S == null || S.length() == 0) {
return;
}
Map<Character, Integer> map = new HashMap<>();
for (char c : S.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> (b.getValue() - a.getValue()));
pq.addAll(map.entrySet());
System.out.println(pq);
所以,我了解到对于这个特定的片段,最高优先级给予具有最大值的键,当我打印队列时,我得到
[a=9, b=4, c=1]
但是当我使用这个比较器时
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> (a.getValue() - b.getValue()));
我不明白为什么会这样
[c=1, a=9, b=4]
我以为b
会排第二,a
会排在最后
第二题
此外,当我添加条目时
Map.Entry<Character, Integer> entry =
new java.util.AbstractMap.SimpleEntry<Character, Integer>('a', 5);
pq.offer(entry);
我得到这个输出
[c=1, a=5, b=4, a=9]
不明白 a
是怎么过去的
引用 PriorityQueue
的 javadoc:
The Iterator provided in method iterator()
is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray())
.
String S = "aaaaaaaacabbbb";
if (S == null || S.length() == 0) {
return;
}
Map<Character, Integer> map = new HashMap<>();
for (char c : S.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> (b.getValue() - a.getValue()));
pq.addAll(map.entrySet());
System.out.println(pq);
所以,我了解到对于这个特定的片段,最高优先级给予具有最大值的键,当我打印队列时,我得到
[a=9, b=4, c=1]
但是当我使用这个比较器时
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> (a.getValue() - b.getValue()));
我不明白为什么会这样
[c=1, a=9, b=4]
我以为b
会排第二,a
会排在最后
第二题
此外,当我添加条目时
Map.Entry<Character, Integer> entry =
new java.util.AbstractMap.SimpleEntry<Character, Integer>('a', 5);
pq.offer(entry);
我得到这个输出
[c=1, a=5, b=4, a=9]
不明白 a
是怎么过去的
引用 PriorityQueue
的 javadoc:
The Iterator provided in method
iterator()
is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider usingArrays.sort(pq.toArray())
.