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
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 转换 ldap 日期 2022-01-01