所以我想使用最小的键作为优先级,然后返回相应键的值:
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());
}
}
我正在寻找的输出是90,因为1是最小的键。即使将值用作优先级并返回键也可以,因为我可以根据需要交换数据。我想使用值/键作为优先级显示键/值(在这种情况下为最小值)。我不知道在这种情况下如何做到这一点。在C ++中可以正常工作。
您需要使用Comparator
,它将用于订购此优先级队列。
创建Comparator.comparing()
时使用Method reference
并通过比较参数的PriorityQueue
PriorityQueue<Pair<Integer,Integer> > pq=
new PriorityQueue<Pair<Integer,Integer>>(n, Comparator.comparing(Pair::getKey));
或
您可以使用lambda表达式
PriorityQueue<Pair<Integer,Integer> > pq=
new PriorityQueue<Pair<Integer,Integer>>(n,(a,b) -> a.getKey() - b.getKey());