How to use pair in a priority queue and then return the value using the key as the priority(如何在优先级队列中使用Pair,然后使用键作为优先级返回值)
本文介绍了如何在优先级队列中使用Pair,然后使用键作为优先级返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我想使用最小的键作为优先级,然后返回相应键的值:
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
。
创建PriorityQueue
时使用Comparator.comparing()
并传递比较参数的Method reference
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());
这篇关于如何在优先级队列中使用Pair,然后使用键作为优先级返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何在优先级队列中使用Pair,然后使用键作为优先级返回值


基础教程推荐
猜你喜欢
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01