使用Hashmap条目中的PriorityQueue创建Minheap
我正在使用PriortityQueue
创建一个 min-heap ,从hashmap
中填充。其中条目
MAP
的对象是Integer
& 整数
。
我正在借助比较器
实现它。使用 value hashmap
进行比较。
我的问题是 - 如何对hashmap
type value 进行比较integer
?
PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o1.getValue() - o2.getValue();
}
});
I am creating a Min-Heap using PriorityQueue
populated from a HashMap
. Where Entry
objects of the Map
are pairs of Integer
& Integer
.
And I'm implementing it with a help of Comparator
. To use Value of HashMap
for comparison.
My question is - How to make comparison of HashMap
entries on Value of type Integer
?
PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o1.getValue() - o2.getValue();
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以首先比较值,然后将密钥类似地进行比较:
You could combine the comparison by first comparing the value and then the key like so:
定义比较器
使用匿名类定义
比较器
不是一个好方法。由于 Java 8 在8年前发布了,因此在这种情况下,我们有另一种选择,甚至是一堆替代方案。
简单明了的lambda表达式:
注:
o1.getValue()会导致结果不正确。
integer.compare()
- 是比较整数值的正确方法。java 8静态方法
比较()
来自比较器
接口:最合适的选项选项。 >从
输入
接口:填充队列
以 queue 使用 entries map ,您可以使用循环的普通
:
或使用
collection> Collection> Collection> COADER
接口条目集:Defining a Comparator
Defining a
Comparator
using an anonymous class isn't a good approach.Since Java 8 which was released more than 8 years ago we have an alternative, or even a bunch of alternatives like in this case.
A simple and straightforward lambda expression:
Note:
o1.getValue() - o2.getValue()
- might cause overflow ofint
value, which will lead to incorrect results.Integer.compare()
- is the proper way to compare integer values.Java 8 static method
comparingInt()
from theComparator
interface:And the most suitable option it this case
comparingByValue()
from theEntry
interface :Populating the Queue
To populate the queue with entries from a map, you can use a plain
for
loop:Or make use of method
forEach()
fromCollection
interface invoked on the entry set: