Java 8 具有按值升序排序的Hashmap的优先级队列
我想按优先级队列中HashMap的值按升序对值进行排序Java 8 具有按值升序排序的Hashmap的优先级队列,java-8,hashmap,priority-queue,Java 8,Hashmap,Priority Queue,我想按优先级队列中HashMap的值按升序对值进行排序 HashMap<Integer, Integer> map = new HashMap<>(); map.put(1, 1); map.put(2, 5); map.put(3, 2); map.put(4,4); PriorityQueue<Map.Entry<Integer, Integer>> minHeap
HashMap<Integer, Integer> map = new HashMap<>();
map.put(1, 1);
map.put(2, 5);
map.put(3, 2);
map.put(4,4);
PriorityQueue<Map.Entry<Integer,
Integer>> minHeap
= new PriorityQueue<>(
(a, b)
-> a.getValue().equals(b.getValue())
? Integer.compare(a.getKey(),
b.getKey())
: Integer.compare(a.getValue(),
b.getValue()));
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
minHeap.add(entry);
}
System.out.println(minHeap);
HashMap map=newhashmap();
图.put(1,1);
地图.put(2,5);
地图.put(3,2);
图.put(4,4);
优先队列最小堆
=新优先级队列(
(a、b)
->a.getValue().equals(b.getValue())
?整数。比较(a.getKey(),
b、 getKey())
:Integer.compare(a.getValue(),
b、 getValue());
对于(Map.Entry:Map.entrySet()){
添加(条目);
}
System.out.println(minHeap);
输出
[1=1,4=4,3=2,2=5]
有人能提出为什么顺序不是按值升序排列的吗这回答了你的问题吗?请注意第二个答案(实际上是我写的)如何解释PriorityQueue只在队列语义(add,poll,…)上尊重排序,而不是在其迭代器上尊重排序(在调用toString时像您一样在内部使用)@GPI我在simliar行上做过,不确定为什么我的答案不正确,如果值相同,那么我检查键问题不是比较器,而是结果的打印。队列的顺序很好,但要真正遵守该顺序,必须将其用作
队列
,而不是可编程序
。例如,当(!minHeap.isEmpty()){System.out.println(minHeap());}@GPI你必须将它用作队列,而不是Iterable,你能解释我在链接答案中做了什么吗(见我的第一条评论)。用作队列
意味着只使用队列
接口中的方法,而不将其用作可编程序
意味着不调用.iterator()
(这是priorityQueue.toString()
内部执行的操作)