Java.是否可以在优先级队列中使用一对,然后使用键作为优先级返回值 [英] Java. Is it possible to use a pair in a priority queue and then return a value using the key as a priority
问题描述
所以我想使用最小的键作为优先级,然后返回该对应键的值:
So I want to use the smallest key as the priority and then return the VALUE of that corresponding key:
import javafx.util.Pair;
import java.util.PriorityQueue;
public class Test
{
public static void main (String[] args)
{
int n = 5;
PriorityQueue <Pair <Integer,Integer> > l = new PriorityQueue <Pair <Integer,Integer> > (n);
l.add(new Pair <> (1, 90));
l.add(new Pair <> (7, 54));
l.add(new Pair <> (2, 99));
l.add(new Pair <> (4, 88));
l.add(new Pair <> (9, 89));
System.out.println(l.poll().getValue());
}
}
Im寻找的输出为90,因为1是最小键.即使将值用作优先级并返回键也可以,因为我可以根据需要交换数据.我想使用值/键作为优先级显示键/值(在这种情况下为最小值).我不知道在这种情况下如何做到这一点.在C ++中可以正常工作.
The output Im looking for is 90 because 1 is the smallest key. Its fine even if the value is used as the priority and the key is returned because I can just swap the data if neccessary. I want to display key/value using value/key as a priority (minimum value in this case). I do not know how this can be done in this scenario. This works fine in C++.
推荐答案
您需要使用比较器
,它将用于订购此优先级队列.
You need to use Comparator
which will be used to order this priority queue.
在创建 PriorityQueue
PriorityQueue<Pair<Integer,Integer> > pq=
new PriorityQueue<Pair<Integer,Integer>>(n, Comparator.comparing(Pair::getKey));
或
您可以使用lambda表达式
You can use lambda expression
PriorityQueue<Pair<Integer,Integer> > pq=
new PriorityQueue<Pair<Integer,Integer>>(n,(a,b) -> a.getKey() - b.getKey());
这篇关于Java.是否可以在优先级队列中使用一对,然后使用键作为优先级返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!